C#设计模式-工厂方法模式

1.定义

定义一个用于创建对象的接口,让子类决定将哪一个类实例化。它使一个类的实例化延迟到其子类。

2.UML图



3.代码

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Factory c1 = new ConcreteFactory1();
            Product p1 = c1.Create();

            Factory c2 = new ConcreteFactory2();
            Product p2 = c2.Create();

            Console.ReadKey();
        }
    }

    /// <summary>
    /// 抽象工厂
    /// </summary>
    abstract class Factory
    {
        public abstract Product Create();
    }

    /// <summary>
    /// 具体工厂
    /// </summary>
    class ConcreteFactory1 : Factory
    {
        public override Product Create()
        {
            Console.WriteLine("创建并返回ConcreteProduct1实例!");
            return new ConcreteProduct1();
        }
    }

    /// <summary>
    /// 具体工厂
    /// </summary>
    class ConcreteFactory2 : Factory
    {
        public override Product Create()
        {
            Console.WriteLine("创建并返回ConcreteProduct2实例!");
            return new ConcreteProduct2();
        }
    }

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

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

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


评论: 0 | 引用: 0 | 查看次数: 5775
发表评论
登录后再发表评论!