以下是一个简单工厂模式的C#实现示例:
using System;
// 抽象产品
interface IProduct
{
void Operation();
}
// 具体产品A
class ConcreteProductA : IProduct
{
public void Operation()
{
Console.WriteLine("具体产品A的操作");
}
}
// 具体产品B
class ConcreteProductB : IProduct
{
public void Operation()
{
Console.WriteLine("具体产品B的操作");
}
}
// 简单工厂
class SimpleFactory
{
public IProduct CreateProduct(string productType)
{
if (productType == "A")
{
return new ConcreteProductA();
}
else if (productType == "B")
{
return new ConcreteProductB();
}
else
{
throw new ArgumentException("无效的产品类型");
}
}
}
class Program
{
static void Main(string[] args)
{
SimpleFactory factory = new SimpleFactory();
// 使用简单工厂创建产品
IProduct productA = factory.CreateProduct("A");
productA.Operation();
IProduct productB = factory.CreateProduct("B");
productB.Operation();
}
}
在上述示例中,抽象产品类IProduct
定义了产品的操作方法Operation
。具体产品类ConcreteProductA
和ConcreteProductB
实现了抽象产品接口。
简单工厂类SimpleFactory
通过CreateProduct
方法根据传入的产品类型来创建具体产品,并返回抽象产品接口。
在主函数中,我们通过简单工厂创建了具体产品A和B,并调用其操作方法。运行结果为:
具体产品A的操作
具体产品B的操作