木子屋 Dnawo's BLOG

C#设计模式-简单工厂模式

👤 dnawo 📅 2010-03-09 👁 6642 👍 0 💬 0 🔄 来源:本站原创
1.定义

根据提供给它的数据,返回几个可能类中的一个类的实例。

2.UML图

图片

3.代码

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Product p;
            p = Factory.Create("product1");
            p = Factory.Create("product2");

            Console.ReadKey();
        }
    }

    /// <summary>
    /// 工厂类
    /// </summary>
    class Factory
    {
        public static Product Create(string type)
        {
            if (type == "product1")
            {
                Console.WriteLine("创建并返回ConcreteProduct1实例!");
                return new ConcreteProduct1();
            }
            else if (type == "product2")
            {
                Console.WriteLine("创建并返回ConcreteProduct2实例!");
                return new ConcreteProduct2();
            }
            else
                return null;
        }
    }

    /// <summary>
    /// 产品父类
    /// </summary>
    class Product
    { }

    /// <summary>
    /// 具体产品
    /// </summary>
    class ConcreteProduct1 : Product
    { }

    /// <summary>
    /// 具体产品
    /// </summary>
    class ConcreteProduct2 : Product
    { }
}

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 戏说23种设计模式 下一篇 → C#设计模式-工厂方法模式