抽象工厂(AbstractFactory)模式 创建型模式
提供一个创建产品族的接口,其每个子类可以生产一系列相关的产品。
c#
// 抽象工厂模式示例
using System;
// 抽象工厂接口
public interface IAbstractFactory
{
IProductA CreateProductA();
IProductB CreateProductB();
}
// 具体工厂1
public class ConcreteFactory1 : IAbstractFactory
{
public IProductA CreateProductA()
{
return new ProductA1();
}
public IProductB CreateProductB()
{
return new ProductB1();
}
}
// 具体工厂2
public class ConcreteFactory2 : IAbstractFactory
{
public IProductA CreateProductA()
{
return new ProductA2();
}
public IProductB CreateProductB()
{
return new ProductB2();
}
}
// 抽象产品A接口
public interface IProductA
{
void MethodA();
}
// 具体产品A1
public class ProductA1 : IProductA
{
public void MethodA()
{
Console.WriteLine("ProductA1.MethodA()");
}
}
// 具体产品A2
public class ProductA2 : IProductA
{
public void MethodA()
{
Console.WriteLine("ProductA2.MethodA()");
}
}
// 抽象产品B接口
public interface IProductB
{
void MethodB();
}
// 具体产品B1
public class ProductB1 : IProductB
{
public void MethodB()
{
Console.WriteLine("ProductB1.MethodB()");
}
}
// 具体产品B2
public class ProductB2 : IProductB
{
public void MethodB()
{
Console.WriteLine("ProductB2.MethodB()");
}
}
// 客户端
public class Client
{
private IAbstractFactory factory;
public Client(IAbstractFactory factory)
{
this.factory = factory;
}
public void Run()
{
IProductA productA = factory.CreateProductA();
IProductB productB = factory.CreateProductB();
productA.MethodA();
productB.MethodB();
}
}
// 测试
public class Test
{
static void Main(string[] args)
{
IAbstractFactory factory1 = new ConcreteFactory1();
Client client1 = new Client(factory1);
client1.Run();
IAbstractFactory factory2 = new ConcreteFactory2();
Client client2 = new Client(factory2);
client2.Run();
Console.ReadKey();
}
}