C# factory and abstract factory
Copy from https://dotnettutorials.net/lesson/abstract-factory-design-pattern-csharp/
“A factory is an object used for creating other objects. In technical terms, we can say that a factory is a class with a method. That method will create and return different objects based on the received input parameter“.
public interface IHuman { void Eat(); void Drink(); } public class HumanFactory { public static IHuman GetHuman(string humanType) { IHuman human = null; if(humanType=="North") { human = new NorthHuman(); } else if(humanType=="South") { human = new SouthHuman(); } return human; } } public class NorthHuman : IHuman { public void Drink() { Console.WriteLine("North drink!"); } public void Eat() { Console.WriteLine("North eat!"); } } public class SouthHuman : IHuman { public void Drink() { Console.WriteLine("South drink!"); } public void Eat() { Console.WriteLine("South drink!"); } } static void FactoryDemo() { IHuman human = HumanFactory.GetHuman("North"); human.Drink(); human.Eat(); }
The Abstract Factory Design Pattern provides a way to encapsulate a group of factories with a common theme without specifying their concrete classes.
public interface IBike { void GetDetails(); } public interface ICar { void GetDetails(); } public class RegularBike : IBike { public void GetDetails() { Console.WriteLine("RegularBike GetDetails()"); } } public class SportsBike : IBike { public void GetDetails() { Console.WriteLine("SportsBike GetDetails()!"); } } public class RegularCar : ICar { public void GetDetails() { Console.WriteLine("RegularCar GetDetails!"); } } public class SportsCar : ICar { public void GetDetails() { Console.WriteLine("SportsCar GetDetails!"); } } public interface IVehicleFactory { IBike CreateBike(); ICar CreateCar(); } public class RegularVehicleFatory : IVehicleFactory { public IBike CreateBike() { return new RegularBike(); } public ICar CreateCar() { return new RegularCar(); } } public class SportsVechicleFactory : IVehicleFactory { public IBike CreateBike() { return new SportsBike(); } public ICar CreateCar() { return new SportsCar(); } } static void AbstractFactoryDemo() { IVehicleFactory regularVehicleFactory = new RegularVehicleFatory(); IBike regularBike = regularVehicleFactory.CreateBike(); regularBike.GetDetails(); ICar regularCar=regularVehicleFactory.CreateCar(); regularCar.GetDetails(); IVehicleFactory sportsVehicleFactory = new SportsVechicleFactory(); IBike sportsBike=sportsVehicleFactory.CreateBike(); sportsBike.GetDetails(); ICar sportsCar=sportsVehicleFactory.CreateCar(); sportsCar.GetDetails(); }