在C#中,简单工厂(Simple Factory)和抽象工厂(Abstract Factory)是两种常用的设计模式,它们都属于创建型设计模式,用于创建对象而无需在代码中显式指定具体的类。尽管它们的目的相似,但在复杂性和灵活性方面存在显著差异。
简单工厂(Simple Factory)
简单工厂模式是一种不属于GoF(四人帮)23种设计模式之一的模式,但它非常流行且广泛使用。它定义了一个创建对象的接口,但让子类决定要实例化的类是哪一个。工厂类使用静态方法来创建对象,客户端可以通过调用这些静态方法来获取所需的实例,而无需指定具体的类。
优点:
- 客户端不需要知道如何创建具体产品的类。
- 减少了代码中的对象创建逻辑,简化了客户端代码。
缺点:
- 如果系统中需要增加新的产品类,则需要修改工厂类,违反了开闭原则(对扩展开放,对修改关闭)。
- 工厂类负责所有产品的创建,这可能会导致工厂类变得非常庞大。
示例代码:
interface Product
{
void Use();
}
class ConcreteProductA : Product
{
public void Use()
{
Console.WriteLine("Using ConcreteProductA");
}
}
class ConcreteProductB : Product
{
public void Use()
{
Console.WriteLine("Using ConcreteProductB");
}
}
class SimpleFactory
{
public static Product CreateProduct(string type)
{
switch (type)
{
case "A":
return new ConcreteProductA();
case "B":
return new ConcreteProductB();
default:
throw new ArgumentException("Unknown product type");
}
}
}
class Program
{
static void Main(string[] args)
{
Product productA = SimpleFactory.CreateProduct("A");
productA.Use();
Product productB = SimpleFactory.CreateProduct("B");
productB.Use();
}
}
抽象工厂(Abstract Factory)
抽象工厂模式提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。客户端不依赖于产品的具体实现,而是依赖于抽象工厂和抽象产品。这允许客户端在不需要修改代码的情况下,就可以更换产品的具体实现。
优点:
- 可以在类的内部使用产品族中的产品,而不需要知道具体的实现。
- 增加了系统的灵活性和可扩展性。
缺点:
- 如果产品族中的产品数量过多,会导致工厂接口过于庞大,难以维护。
- 系统扩展复杂,如果需要添加新的产品族,就需要修改抽象工厂类及其所有子类。
示例代码(假设有两个产品族:GUI和CLI):
interface IButton
{
void Paint();
}
interface IText
{
void Write();
}
class GuiButton : IButton
{
public void Paint()
{
Console.WriteLine("GUI Button painted");
}
}
class GuiText : IText
{
public void Write()
{
Console.WriteLine("GUI Text written");
}
}
class CliButton : IButton
{
public void Paint()
{
Console.WriteLine("CLI Button painted");
}
}
class CliText : IText
{
public void Write()
{
Console.WriteLine("CLI Text written");
}
}
interface IFactory
{
IButton CreateButton();
IText CreateText();
}
class GuiFactory : IFactory
{
public IButton CreateButton()
{
return new GuiButton();
}
public IText CreateText()
{
return new GuiText();
}
}
class CliFactory : IFactory
{
public IButton CreateButton()
{
return new CliButton();
}
public IText CreateText()
{
return new CliText();
}
}
class Program
{
static void Main(string[] args)
{
IFactory guiFactory = new GuiFactory();
guiFactory.CreateButton().Paint();
guiFactory.CreateText().Write();
IFactory cliFactory = new CliFactory();
cliFactory.CreateButton().Paint();
cliFactory.CreateText().Write();
}
}
在这个例子中,IFactory
是一个抽象工厂接口,定义了创建按钮和文本对象的方法。GuiFactory
和 CliFactory
是具体的工厂类,分别实现了 IFactory
接口,并返回特定于GUI和CLI的产品对象。