例子如下:
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); } }