抽象工厂模式(Abstract Factory)

作者:追风剑情 发布于:2016-6-17 17:41 分类:设计模式

应用场景:创建产品簇

using System;
using System.Collections.Generic;
using System.Text;

namespace FactoryTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ConcreteFactoryA fA = new ConcreteFactoryA();
            ConcreteFactoryB fB = new ConcreteFactoryB();

            IProduct pA1 = fA.CreateProduct1();
            IProduct pA2 = fA.CreateProduct2();

            IProduct pB1 = fB.CreateProduct1();
            IProduct pB2 = fB.CreateProduct2();

            Console.Read();
        }
    }

    public class IProduct
    {
        void Show();
    }


    //A类产品
    public class ProductA1 : IProduct
    {
        public void Show(){}
    }

    public class ProductA2 : IProduct
    {
        public void Show() { }
    }

    //B类产品
    public class ProductB1 : IProduct
    {
        public void Show(){}
    }

    public class ProductB2 : IProduct
    {
        public void Show() { }
    }

    //工厂接口
    public interface IFactory
    {
        void CreateProduct1();
        void CreateProduct2();
    }

    //具体工厂
    //一种工厂生产一类产品
    public class ConcreteFactoryA : IFactory
    {
        public IProduct CreateProduct1()
        {
            return new ProductA1();
        }

        public IProduct CreateProduct2()
        {
            return new ProductA2();
        }
    }

    public class ConcreteFactoryB : IFactory
    {
        public IProduct CreateProduct1()
        {
            return new ProductB1();
        }

        public IProduct CreateProduct2()
        {
            return new ProductB2();
        }
    }
}

标签: 设计模式

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号