通过工厂类封装对象的创建逻辑,客户端无需直接实例化具体类。
// 产品接口 public interface IProduct { void ShowInfo(); } // 具体产品A public class ProductA : IProduct { public void ShowInfo() => Console.WriteLine("这是产品A"); } // 具体产品B public class ProductB : IProduct { public void ShowInfo() => Console.WriteLine("这是产品B"); } // 工厂类 public class ProductFactory { public static IProduct CreateProduct(string type) { return type switch { "A" => new ProductA(), "B" => new ProductB(), _ => throw new ArgumentException("无效的产品类型") }; } } // 调用示例 public static void TestFactory() { IProduct product = ProductFactory.CreateProduct("A"); product.ShowInfo(); }