设计模式之抽象工厂模式(AbstractFactory)
作者:互联网
抽象工厂的定义
代码实现
namespace ConsoleApplication1.AbstractFactory
{
/// <summary>
/// 抽象工厂
/// </summary>
abstract class AbstractFactory
{
// Methods
public abstract AbstractProductA CreateProductA();
public abstract AbstractProductB CreateProductB();
}
/// <summary>
/// 具体工厂1
/// </summary>
class ConcreteFactory1 : AbstractFactory
{
// Methods
public override AbstractProductA CreateProductA()
{
return new ProductA1();
}
public override AbstractProductB CreateProductB()
{
return new ProductB1();
}
}
/// <summary>
/// 具体工厂2
/// </summary>
class ConcreteFactory2 : AbstractFactory
{
// Methods
public override AbstractProductA CreateProductA()
{
return new ProductA2();
}
public override AbstractProductB CreateProductB()
{
return new ProductB2();
}
}
// "Client" - the interaction environment of the products
class Environment
{
// Fields
private readonly AbstractProductA AbstractProductA;
private readonly AbstractProductB AbstractProductB;
// Constructors
public Environment(AbstractFactory factory)
{
AbstractProductB = factory.CreateProductB();
AbstractProductA = factory.CreateProductA();
}
// Methods
public void Run()
{
AbstractProductB.Interact(AbstractProductA);
}
}
}
调用方代码如下:
class ClientApp
{
public void Start()
{
AbstractFactory factory1 = new ConcreteFactory1();
Environment e1 = new Environment(factory1);
e1.Run();
AbstractFactory factory2 = new ConcreteFactory2();
Environment e2 = new Environment(factory2);
e2.Run();
}
}
要点总结
.Net框架中用到的抽象工厂模式:
标签:AbstractProductA,AbstractProductB,Environment,抽象,AbstractFactory,new,设计模式,public 来源: https://blog.csdn.net/qq_29821795/article/details/119274052