简单工厂模式
定义
public interface ICar { public void Drive(); } public class XiaoMiCar : ICar { public void Drive() { Console.WriteLine("正在驾驶小米汽车"); } } public class TeslaCar : ICar { public void Drive() { Console.WriteLine("正在驾驶特斯拉"); } } public static class CarFacotry { public static ICar CreateCar(string cartype) { switch (cartype) { case "xiaomi":return new XiaoMiCar(); case "tesla":return new TeslaCar(); default:return null; } } }
调用
Console.WriteLine("简单工厂模式"); ICar car = CarFacotry.CreateCar("xiaomi"); car.Drive(); ICar car1 = CarFacotry.CreateCar("tesla"); car1.Drive();
喜欢 C#、SQL、Web