C# 中的工厂模式(Factory Pattern)是一种创建型设计模式,它提供了一种创建对象的最佳方式,而无需在代码中显式指定要创建的具体类。工厂模式的核心在于将对象的创建逻辑封装在一个专门的工厂类中,这样当需要创建对象时,客户端只需向工厂类发送请求,而无需知道对象的创建细节。
工厂模式主要分为三种类型:简单工厂模式(Simple Factory Pattern)、工厂方法模式(Factory Method Pattern)和抽象工厂模式(Abstract Factory Pattern)。
1. 简单工厂模式
简单工厂模式(也称为静态工厂方法模式)是最简单的工厂模式。它由一个工厂类根据传入的参数决定实例化哪一个类。
示例代码:
csharp复制代码
// 产品接口 | |
public interface IProduct | |
{ | |
void Use(); | |
} | |
// 具体产品A | |
public class ConcreteProductA : IProduct | |
{ | |
public void Use() | |
{ | |
Console.WriteLine("Using Product A"); | |
} | |
} | |
// 具体产品B | |
public class ConcreteProductB : IProduct | |
{ | |
public void Use() | |
{ | |
Console.WriteLine("Using Product B"); | |
} | |
} | |
// 工厂类 | |
public class ProductFactory | |
{ | |
public static IProduct CreateProduct(string type) | |
{ | |
switch (type) | |
{ | |
case "A": | |
return new ConcreteProductA(); | |
case "B": | |
return new ConcreteProductB(); | |
default: | |
throw new InvalidOperationException("Invalid product type"); | |
} | |
} | |
} | |
// 客户端代码 | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
IProduct productA = ProductFactory.CreateProduct("A"); | |
productA.Use(); | |
IProduct productB = ProductFactory.CreateProduct("B"); | |
productB.Use(); | |
} | |
} |
2. 工厂方法模式
工厂方法模式将对象的创建延迟到子类中进行。工厂方法让类的实例化推迟到子类中进行。
示例代码(省略部分细节):
csharp复制代码
// 抽象产品 | |
public abstract class Product | |
{ | |
public abstract void Use(); | |
} | |
// 具体产品A | |
public class ConcreteProductA : Product | |
{ | |
public override void Use() | |
{ | |
// 实现 | |
} | |
} | |
// 抽象工厂 | |
public abstract class Creator | |
{ | |
public abstract Product FactoryMethod(); | |
public void SomeOperation() | |
{ | |
Product product = FactoryMethod(); | |
product.Use(); | |
} | |
} | |
// 具体工厂 | |
public class ConcreteCreatorA : Creator | |
{ | |
public override Product FactoryMethod() | |
{ | |
return new ConcreteProductA(); | |
} | |
} | |
// 客户端代码 | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Creator creator = new ConcreteCreatorA(); | |
creator.SomeOperation(); | |
} | |
} |
3. 抽象工厂模式
抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
示例代码(较为复杂,省略具体实现细节):
抽象工厂模式通常涉及到多个产品接口和多个具体产品类,以及相应的工厂接口和具体工厂类,用于创建产品家族的不同组合。
总的来说,工厂模式通过封装对象的创建过程,降低了客户端与具体产品类之间的耦合,提高了系统的灵活性和可扩展性。在实际开发中,可以根据具体需求选择适合的工厂模式。