C#设计模式05——抽象工厂的写法

产品

抽象产品一

    //鼠标抽象类
    public abstract class Mouse
    {
        public abstract void Print();
    }

具体产品

    //联想鼠标
    public class LenovoMouse : Mouse
    {
        public override void Print()
        {
            Console.WriteLine("生产了一个联想鼠标");
        }
    }
    //惠普鼠标
    public class HPMouse : Mouse
    {
        public override void Print()
        {
            Console.WriteLine("生产了一个惠普鼠标");
        }
    }

抽象产品二

    //键盘抽象类
    public abstract class Keybo
    {
        public abstract void Print();
    }

具体产品

    //惠普键盘
    public class HpKeybo : Keybo
    {
        public override void Print()
        {
            Console.WriteLine("生产了一个惠普键盘!");
        }
    }
    //戴尔键盘类
    public class DellKeybo : Keybo
    {
        public override void Print()
        {
            Console.WriteLine("生产了一个戴尔键盘!");
        }
    }

工厂

抽象工厂

    /// <summary>
    /// Pc产品工厂抽象类
    /// </summary>
    public abstract class PcFactory
    {
        public abstract Mouse CreateMouse();
        public abstract Keybo CreateKeybo();
    }

具体工厂

    //戴尔pc工厂
    public class DellPcFactroy : PcFactory
    {
        public override Keybo CreateKeybo()
        {
            return new DellKeybo();
        }

        public override Mouse CreateMouse()
        {
            return new DellMouse();
        }
    }
    //惠普pc工厂
    public class HpPcFactory : PcFactory
    {
        public override Mouse CreateMouse()
        {
            return new HPMouse();
        }
        public override Keybo CreateKeybo()
        {
            return new HpKeybo();
        }

    }

运行测试

                //生产一个戴尔鼠标
                MouseFactory dellMouseFactory = new DellMouseFactroy();
                _04工厂模式.Mouse dellMouse = dellMouseFactory.CreateMouse();
                dellMouse.Print();

                //生产一个惠普鼠标
                MouseFactory hpMouseFactory = new HpMouseFactory();
                _04工厂模式.Mouse hpMouse = hpMouseFactory.CreateMouse();
                hpMouse.Print();

                //生产一个联想鼠标
                LenovoMouseFactory lenovoMouseFactory = new LenovoMouseFactory ();
                _04工厂模式.Mouse lenovoMouse = lenovoMouseFactory.CreateMouse();
                lenovoMouse.Print();

C#设计模式05——抽象工厂的写法

 

上一篇:linux – 鼠标点击fedora上的声音


下一篇:【Java】【多态】随机创建子类对象