I have subcategories defined under Vehicle Class as :-
Bike
Car
truck
bus
Further, there are different variants under each four categories
Bike :- sport, standard
Car :- sport, standard, electric
3.Truck :- Mini Truck , Power Truck
Bus:- Mini Bus, AC Bus
We have to calculate the price of each variants defined in each category.
Example 1 : With Constructor overloading
public interface ivehicle
{
public void calculateprice();
}
public class calculatprice : ivehicle
{
public void calculateprice() {
}
}
public class bike_1
{
public readonly ivehicle vehicle;
public bike_1(string model) {
if (model == "STANDARD")
{
Console.WriteLine("THe price of standard is 1 lac");
}
else if (model == "SPORTS")
{
Console.WriteLine("The price of sports is 2 lacs");
}
}
}
Example 2:- With using overiding function and inheritance
public class vehicle_3
{
}
public class bike_3: vehicle_3
{
public virtual void Calculateprice_3() { }
}
public class sports_3 :bike_3
{
public override void Calculateprice_3()
{
base.Calculateprice_3();
Console.WriteLine("The price of Sports is 2 lacs");
}
}
public class standard_3 : bike_3
{
public override void Calculateprice_3()
{
base.Calculateprice_3();
Console.WriteLine("The price of standard is 1 lacs");
}
}
Example 3:- With interface
public class vehicle_4
{
}
public interface ivehicle_4
{
void CalculatePrice_4();
}
public class bike_4 :ivehicle_4
{
public virtual void CalculatePrice_4() { }
}
public class sports_4 : bike_4
{
public override void CalculatePrice_4()
{
base.CalculatePrice_4();
Console.WriteLine("The price of Sports is 2 lacs");
}
}
public class standard_4 : bike_4
{
public override void CalculatePrice_4()
{
base.CalculatePrice_4();
Console.WriteLine("The price of standard is 1 lacs");
}
}
Related
I have a Factory that looks at some property to determine if the value T should be provided. How can I use this with HK2 in an abstract binder?
public interface Printer {
void print(String str);
}
public ConsolePrinter implements Printer {
public void print(String str) {
System.out.println(str);
}
}
public PrinterFactory implements Factory<Optional<Printer>> {
boolean isPrinterAvailable;
public PrinterFactory(boolean isPrinterAvailable) {
this.isPrinterAvailable = isPrinterAvailable;
}
public Optional<Printer> provide() {
if (this.isPrinterAvailable) {
return new ConsolePrinter();
}
return Optional.empty();
}
}
public class Binder extends AbstractBinder {
protected void configure() {
// ?????
bindFactory(PrinterFactory.class).to(Printer.class);
}
}
Any help/documentation/examples is much appreciated!
I am using springfox version 2.9.2 and swagger annotations 1.5.x. The ApiModel annotations support the discriminator, subTypes and parent attribute which are required to make polymorphism work but I am not seeing the correct apidocs generated to enable polymorphism.
Here is my annotated code.
#RestController
#RequestMapping("/api/vehicles")
public class VehicleController {
private static final Logger LOGGER = LoggerFactory.getLogger(VehicleController.class);
#PostMapping(consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE})
void post(#RequestBody Vehicle anyVehicle) {
LOGGER.info("Vehicle : {}", anyVehicle);
}
}
#ApiModel(discriminator = "type", subTypes = {Car.class, Bike.class})
public class Vehicle {
String brand;
String type;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
#ApiModel(parent = Vehicle.class)
public class Car extends Vehicle {
int noOfDoors;
boolean powerWindows;
public int getNoOfDoors() {
return noOfDoors;
}
public void setNoOfDoors(int noOfDoors) {
this.noOfDoors = noOfDoors;
}
public boolean isPowerWindows() {
return powerWindows;
}
public void setPowerWindows(boolean powerWindows) {
this.powerWindows = powerWindows;
}
}
#ApiModel(parent = Vehicle.class)
public class Bike extends Vehicle {
boolean pillion;
public boolean isPillion() {
return pillion;
}
public void setPillion(boolean pillion) {
this.pillion = pillion;
}
}
When the docs get generated is basically shows one endpoint which handles a POST request and takes in a Vehicle as the model.
Is what I am doing here supposed to work? Can someone point me to a working example of this with SpringFox that I can look at?
Support for discriminator is not available in Swagger UI yet. You can follow these issues for status updates:
Discriminator does not switch schema
subTypes not displayed in model
Premisse:
I am folowing IUnitOfWork Patterns I created a Base class with my methods to persist data.
My Problem:
I found a problem to write a method Next Number of table from SQLServer, because of this, I am repeating this method in every class .
Classes:
BaseContext Class:
public class BaseContext<T> : DbContext where T : class
{
public DbSet<T> DbSet
{
get;
set;
}
public BaseContext() : base("DefaultConnection")
{
Database.SetInitializer<BaseContext<T>>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// Class Mapping from IMapping
var typesToMapping = (from x in Assembly.GetExecutingAssembly().GetTypes()
where x.IsClass && typeof(IMapping).IsAssignableFrom(x)
select x).ToList();
foreach (var mapping in typesToMapping)
{
dynamic mappingClass = Activator.CreateInstance(mapping);
modelBuilder.Configurations.Add(mappingClass);
}
}
public virtual void ChangeObjectState(object model, EntityState state)
{
((IObjectContextAdapter)this)
.ObjectContext
.ObjectStateManager
.ChangeObjectState(model, state);
}
// Implement IUnitOfWork
public virtual int Save(T model)
{
this.DbSet.Add(model);
this.ChangeObjectState(model, EntityState.Added);
return this.SaveChanges();
}
public virtual int Update(T model, int id)
{
var entity = DbSet.Find(id);
this.Entry(entity).CurrentValues.SetValues(model);
return this.SaveChanges();
}
public virtual void Delete(T model)
{
var entry = this.Entry(model);
if (entry.State == EntityState.Detached)
this.DbSet.Attach(model);
this.ChangeObjectState(model, EntityState.Deleted);
this.SaveChanges();
}
public virtual IEnumerable<T> GetAll()
{
return this.DbSet.ToList();
}
public virtual T GetById(object id)
{
return this.DbSet.Find(id);
}
public virtual IEnumerable<T> Where(Expression<Func<T, bool>> expression)
{
return this.DbSet.Where(expression);
}
public IEnumerable<T> OrderBy(Expression<Func<T, bool>> expression)
{
return this.DbSet.OrderBy(expression);
}
}
My method NextNumber in every class:
public class VersionDao : BaseContext<Version>, IUnitOfWork<Version>
{
public int Next() => DbSet.Max(x => x.VersionId) + 1;
}
public class TicketDao : BaseContext<ViewModelTicket> , IUnitOfWork<ViewModelTicket>
{
public int Next() => DbSet.Max(x => x.TicketId) + 1;
}
public class CompanyDao : BaseContext<Company>, IUnitOfWork<Company>
{
public int Next() => DbSet.Max(x => x.CompanyId) + 1;
}
Solicitation:
I need a suggestions to stop repeatition on Next method in every class.
Thank you
There is no need to implement Unit of Work pattern if you are using Entity Framework. If you click F12/Go To Definition on DbContext you'll see the following summary
A DbContext instance represents a combination of the Unit Of Work and
Repository patterns such that it can be used to query from a database
and group together changes that will then be written back to the store
as a unit. DbContext is conceptually similar to ObjectContext.
I am having a difficult time figuring out how to create a 1:1 mapping between objects in a container using AutoFac. I am getting resolution errors and the documentation is too terse with not enough examples.
Here's the rule I would like to use to resolve my dependencies:
An IHouse object can only be constructed using an IDoor parameter of a specific concrete type, creating a 1:1 mapping between IHouse and IDoor types.
As am example, using the code below, if I resolve the container using a MonkeyDoor, it should give me back a fully constructed MonkeyHouse and only a MonkeyHouse object.
[TestClass]
public class HousingDeveloperTest
{
[TestMethod]
public void TestMethod1()
{
// Load them from an assembly or disc. We are interested in IHouse and IDoor types
var builder = new ContainerBuilder();
// Get all the houses
var assembly = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.Name.EndsWith(nameof(House))).AsImplementedInterfaces();
// get all the doors
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.Name.EndsWith(nameof(Door))).AsImplementedInterfaces();
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var house = container.Resolve<IDoor>(new TypedParameter(typeof(MonkeyDoor), new MonkeyDoor()));
}
}
}
public interface IDoor
{
void Open();
}
public abstract class Door : IDoor
{
public void Open()
{
Trace.WriteLine($"Opening {GetType().ToString()}.");
}
}
// Only works with Victorian homes
public class VictorianDoor : Door
{
}
// Only works with Craftsman homes
public class CraftsmanDoor : Door
{
}
// Only works with monkey homes
public class MonkeyDoor : Door
{
}
public interface IHouse
{
void OpenHouse();
}
public abstract class House : IHouse
{
public IDoor Door;
protected House(IDoor door)
{
Door = door;
Trace.WriteLine($"Building this {this.GetType()} with {door.GetType()} door.");
}
public void OpenHouse()
{
Trace.WriteLine($"We're having an open house on this wonderful {this.GetType().ToString()}.");
Door.Open();
}
}
// Doors must match the homes. (i.e. No monkey doors on a Victorian or Craftsman home.)
public class VictorianHouse : House
{
public VictorianHouse(VictorianDoor door) : base(door)
{
}
}
public class CraftsmanHouse : House
{
public CraftsmanHouse(CraftsmanDoor door) : base(door)
{
}
}
public class MonkeyHouse : House
{
public MonkeyHouse(MonkeyDoor door) : base(door)
{
}
}
I am trying to swap a nested dependency when resolving a specific instance using StructureMap. In 2.x I was able to do this with the following UseSpecial code, but it does not work in 3.x
The code is basically saying... when requesting an instance of IObject, swap the default instance for ITwo with AnotherTwo which is a dependency of IObject's dependency.
public class MyStructureMapRegistry : Registry
{
public MyStructureMapRegistry()
{
For<IObject>().UseSpecial(cfg => cfg.ConstructedBy(x =>
{
x.RegisterDefault(typeof(ITwo), x.GetInstance<AnotherTwo>());
return x.GetInstance<DependsOnOne>();
}));
}
}
The following is the sample object graph that I am trying to wire up.
public interface IObject { }
public interface IOne { }
public interface ITwo { }
public class DependsOnOne : IObject
{
IOne _one;
public DependsOnOne(IOne one)
{
_one = one;
}
}
public class DependsOnTwo : IOne
{
ITwo _two;
public DependsOnTwo(ITwo two)
{
_two = two;
}
}
public class Two : ITwo { }
public class AnotherTwo : ITwo { }