设计模式之抽象工厂模式(AbstractFactory)

抽象工厂的定义

设计模式之抽象工厂模式(AbstractFactory)
设计模式之抽象工厂模式(AbstractFactory)
设计模式之抽象工厂模式(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();
        }
    }

要点总结

设计模式之抽象工厂模式(AbstractFactory)
.Net框架中用到的抽象工厂模式:
设计模式之抽象工厂模式(AbstractFactory)

上一篇:Spring系列.Environment接口


下一篇:conda 切换 python 环境 vscode