C#设计模式-抽象工厂模式



1.定义

提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

2.UML图



3.代码

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            AbstractProductA pa;
            AbstractProductB pb;

            AbstractFactory f1 = new ConcreteFactory1();
            pa = f1.CreateProductA();
            pb = f1.CreateProductB();

            AbstractFactory f2 = new ConcreteFactory2();
            pa = f2.CreateProductA();
            pb = f2.CreateProductB();

            Console.ReadKey();
        }
    }

    /// <summary>
    /// 抽象工厂
    /// </summary>
    abstract class AbstractFactory
    {
        public abstract AbstractProductA CreateProductA();
        public abstract AbstractProductB CreateProductB();
    }

    /// <summary>
    /// 具体工厂
    /// </summary>
    class ConcreteFactory1 : AbstractFactory
    {
        public override AbstractProductA CreateProductA()
        {
            Console.WriteLine("创建并返回ProductA1实例!");
            return new ProductA1();
        }

        public override AbstractProductB CreateProductB()
        {
            Console.WriteLine("创建并返回ProductB1实例!");
            return new ProductB1();
        }
    }

    /// <summary>
    /// 具体工厂
    /// </summary>
    class ConcreteFactory2 : AbstractFactory
    {
        public override AbstractProductA CreateProductA()
        {
            Console.WriteLine("创建并返回ProductA2实例!");
            return new ProductA2();
        }

        public override AbstractProductB CreateProductB()
        {
            Console.WriteLine("创建并返回ProductB2实例!");
            return new ProductB2();
        }
    }

    /// <summary>
    /// 抽象产品
    /// </summary>
    class AbstractProductA
    { }

    /// <summary>
    /// 具体产品
    /// </summary>
    class ProductA1 : AbstractProductA
    { }

    /// <summary>
    /// 具体产品
    /// </summary>
    class ProductA2 : AbstractProductA
    { }

    /// <summary>
    /// 抽象产品
    /// </summary>
    class AbstractProductB
    { }

    /// <summary>
    /// 具体产品
    /// </summary>
    class ProductB1 : AbstractProductB
    { }

    /// <summary>
    /// 具体产品
    /// </summary>
    class ProductB2 : AbstractProductB
    { }
}


评论: 0 | 引用: 0 | 查看次数: 3885
发表评论
登录后再发表评论!