鸟语天空
抽象工厂模式(Abstract Factory)
post by:追风剑情 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();
        }
    }
}

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容