C# 简单工厂模式

using System;

namespace SimpleFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            //简单工厂模式,拥有一个直接创建产品的类
            //使用者需要知道:工厂,产品类别,产品接口即可使用,对使用者隐藏了创建
            IMouse[] myMouse = new IMouse[2];
            myMouse[0]=MouseFactory.CreateMouse(MouseBand.HPMouse);
            myMouse[1]=MouseFactory.CreateMouse(MouseBand.DellMouse);
            foreach (IMouse m in myMouse) { m.SayHi(); }
        }
    }
    //鼠标工厂
    public partial class MouseFactory
    {
        public static IMouse CreateMouse(MouseBand band)
        {
            switch (band)
            {
                case MouseBand.HPMouse:
                    return new HPMouse();
                default:
                    return new DellMouse();
            }
        }
    }
    //公开的品牌
    public enum MouseBand { HPMouse, DellMouse }
    //公开的接口
    public interface IMouse
    {
        void SayHi();
    }
    //隐藏的鼠标实现,避免使用者直接创建
    public partial class MouseFactory
    {
        private class HPMouse : IMouse
        {
            public void SayHi()
            {
                Console.WriteLine("Hi! {0}", this);
            }
        }

        private class DellMouse : IMouse
        {
            public void SayHi()
            {
                Console.WriteLine("Hi! {0}", this);
            }
        }
    }
}

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