C# 抽象工厂模式

using System;

namespace AbstractFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            //抽象工厂模式,主要用来生产具备特定关系的产品
            //增加品牌容易,扩展工厂即可;增加品种难,修改涉及太多
            IFactory[] gc = { new HPFactory(), new DellFactory() };
            foreach (IFactory c in gc)
            {
                Console.WriteLine(">>>>{0}的键鼠套装:", c);
                c.CreateKeyboard().SayHi();
                c.CreateMouse().SayHi();
                Console.WriteLine();
            }
        }
    }

    //鼠标接口:鼠标必须具备的功能
    public interface IMouse
    {
        void SayHi();
    }
    //键盘接口:键盘必须具备的功能
    public interface IKeyboard
    {
        void SayHi();
    }
    //工厂接口:实现接口的为合格工厂
    public interface IFactory
    {
        IMouse CreateMouse();
        IKeyboard CreateKeyboard();
    }

    public class HPFactory : IFactory
    {
        //隐藏的鼠标实现,避免使用者直接创建
        //这里应该是一个复杂对象,但使用者无须了解且不能随意创建
        private class HPMouse : IMouse
        {
            public void SayHi()
            {
                Console.WriteLine("Hi! {0}", this);
            }
        }
        //成套产品,产品之间具有关联性
        private class HPKeyboard : IKeyboard
        {
            public void SayHi()
            {
                Console.WriteLine("Hi! {0}", this);
            }
        }
        public IMouse CreateMouse()
        {
            return new HPMouse();
        }
        public IKeyboard CreateKeyboard()
        {
            return new HPKeyboard();
        }
    }

    public class DellFactory : IFactory
    {
        private class DellMouse : IMouse
        {
            public void SayHi()
            {
                Console.WriteLine("Hi! {0}", this);
            }
        }
        private class DellKeyboard : IKeyboard
        {
            public void SayHi()
            {
                Console.WriteLine("Hi! {0}", this);
            }
        }
        public IMouse CreateMouse()
        {
            return new DellMouse();
        }
        public IKeyboard CreateKeyboard()
        {
            return new DellKeyboard();
        }
    }
}

你可能感兴趣的:(C#)