Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- internal delegate T Instantiate<out T>(/*parameters*/) where T : Vehicle;
- internal interface IVehicle{/*...*/}
- public class Vehicle
- {
- //constructor is not protected. so this cant be intertied from outside assembly.
- internal Vehicle(/*parameters*/){ }
- }
- public class Car : Vehicle
- {
- internal Car(/*parameters*/) : base(/*parameters*/) { }
- }
- /// <summary>
- /// Choose from one of predefined containers to create your vehicle from factoy.
- /// </summary>
- /// <typeparam name="T">type of vehicle</typeparam>
- public class InstanceContainer<T> where T : Vehicle
- {
- internal InstanceContainer(Instantiate<T> instance) // internal
- {
- GetInstance = instance;
- }
- // delegate which creates new instance of T
- internal Instantiate<T> GetInstance { get; }
- }
- /// <summary>
- /// Choose this to create car from factory.
- /// </summary>
- public static InstanceContainer<Car> CarInstance { get; } = new InstanceContainer<Car>(CreateCar);
- private static readonly Instantiate<Car> CreateCar = (/*parameters*/) => new Car(/*parameters*/);
- // ... others options like Plane, Ship etc
- public static T CreateVehicle<T>(/*parameters,*/ InstanceContainer<T> instance) where T : Vehicle
- {
- T obj;
- //...
- // At some point:
- obj = instance.GetInstance(/*parameters*/);
- //...
- return obj;
- }
- VehicleFactory.CreateVehicle(/*parameters,*/ VehicleFactory.CarInstance);
- // turns long name into short one!
- using VehicleInstance = Factories.VehicleFactory.InstanceContainer<Factories.Goods.Vehicle>
- //...
- //...
- VehicleInstance instance;
- // instance will be choosen based on some conditions. like this:
- if(true)
- instance = VehicleFactory.CarInstance; // we got magic co-variant here!
- else
- instance = VehicleFactory.PlaneInstance;
- VehicleFactory.CreateVehicle(/*parameters,*/ instance);
- public interface IContainer<out T>
- {
- // empty!
- }
- internal class InstanceContainer<T> : IContainer<T> where T : Vehicle
- {
- internal InstanceContainer(Instance<T> instance)
- {
- GetInstance = instance;
- }
- internal Instance<T> GetInstance { get; }
- }
- // works fine!
- public static IContainer<Car> CarInstance { get; } = new InstanceContainer<Car>(CreateCar);
- public static T CreateVehicle<T>(/*parameters,*/ IContainer<T> instance)
- {
- T obj;
- //...
- // At some point:
- obj = ((InstanceContainer<T>)instance).GetInstance(/*parameters*/); // runtime error.
- //...
- return obj;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement