31、面向对象设计模式之工厂方法模式概念的提升
例子如下:
public abstract class Product{ public string productName; } public abstract class ProductFactory{ public Product FactoryMethod(string producTypeName){ Product product; product = CreateProduct(producTypeName); return product; } public abstract CreateProduct(string productName); } public class ProductA : Product{ public ProductA(){ productName = "ProductA"; } } public class ProductB : Product{ public ProductB(){ productName = "ProductB"; } } public class ProductC : Product{ public ProductC(){ productName = "ProductC"; } } public class ProductD : Product{ public ProductD(){ productName = "ProductD"; } } public class ProductFactoryA : ProductFactory{ public override Product CreateProduct(string producName){ switch(producName){ case "A": return new ProductA(); case "B": return new ProductB(); } return null; } } public class ProductFactoryB :ProductFactory{ public override Product CreateProduct(string producName){ switch(producName){ case "C": return new ProductC(); case "D": return new ProductD(); } return null; } } class Program{ static void Main(string[] args){ ProductFactory myProductFactory = new ProductFactoryA(); Product myProduct = myProductFactory.FactoryMethod("A"); Console.WriteLine(myProduct.productName); myProduct = myProduct.FactoryMethod("B"); Console.WriteLine(myProduct.producName); ProductFactory myProductFactoryB = new ProductFactoryB(); Product myProductB = myProductFactoryB.FactoryMethod("C") Console.WriteLine(myProductB.producName); myProductB = myProductFactoryB.FactoryMethod("D"); Console.WriteLine(myProduct.producName); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步