您的位置:首页 > 其它

一看就懂的设计模式(二,工厂模式)

2016-05-19 07:48 288 查看
本文是在简单工厂的基础上进行编写的,可以参考简单工厂比较学习,看看都有哪些异同。

namespace 工厂模式
{
    class Program
    {
        static void Main(string[] args)
        {
            IFactory dogF = new DogFactory();
            Animal dog1 = dogF.GetInstance();
            dog1.Show();

            IFactory pigF = new PigFactory();
            Animal pig1 = pigF.GetInstance();
            pig1.Show();

            Console.ReadKey();
        }
    }

    /// <summary>
    /// 先定义一个基类
    /// </summary>
    public class Animal
    {
        public virtual void Show() { }
    }

    /// <summary>
    /// 子类继承基类
    /// </summary>
    public class Dog : Animal
    {
        public override void Show()
        {
            Console.WriteLine("这是dog类方法");
        }
    }

    public class Pig : Animal
    {
        public override void Show()
        {
            Console.WriteLine("这是pig类方法");
        }
    }

    /// <summary>
    /// 工厂类
    /// </summary>
    public interface IFactory
    {
        Animal GetInstance();
    }

    /// <summary>
    /// 具体的工厂
    /// </summary>
    public class DogFactory : IFactory
    {

        public Animal GetInstance()
        {
            return new Dog();
        }
    }

    public class PigFactory : IFactory
    {

        public Animal GetInstance()
        {
            return new Pig();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: