简单工厂

因为我实习了有一个月了,所以想把一些公司里面学习的东西记录下来,就想起了写博客。有什么地方写得不好的,请大家见谅。也希望大家多多指教。

最近在公司看设计模式的东西,就先写写我对一些模式的看后心得。

  今天要写的是简单工厂。因为它是设计模式里面最简单的,可以说是简单的不算设计模式了。所以先拿它来写。

  简单工厂是工厂家族里面最简单的一个设计模式,但是存在必有道理。它也有它的亮点。先来看看它的类图

它的类图很简单,主要有两部分组成,1简单工厂类, 2产品类。因为根据依赖倒转原则。它使用了一个借口来稳定控制具体的产品类的使用,运用了多态的面向对象技术。而在SimpleFactory类的factory方法里面,有一定的逻辑关系来实例化哪个具体的产品类--Product_A或者Product_B。

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Design_Mode.Simple_Factory
{
    public interface IProduct
    {
        void operation();                
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Design_Mode.Simple_Factory
{
    class Product_A : IProduct
    {
        #region IProduct 成员

        public void operation()
        {
            Console.Write("Product_A\n");
        }

        #endregion
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Design_Mode.Simple_Factory
{
    class Product_B : IProduct
    {
        #region IProduct 成员

        public void operation()
        {
            Console.Write("Product_B\n");
        }

        #endregion
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Design_Mode.Simple_Factory
{
    class SimpleFactory
    {
        public static IProduct factory(string param)
        {
            switch (param)
            {
                case "A":
                    return new Product_A();                    
                case "B":
                    return new Product_B();
                default:
                    return null;
            }
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Design_Mode.Simple_Factory;

namespace Design_Mode
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 简单工厂 例子

            IProduct product = SimpleFactory.factory("A");
            
            if(product != null)
                product.operation();

            #endregion

        }
    }
}

  

优点:通过依赖倒置原则,隐藏了具体产品类。而只暴露出来两个类SimpleFactory和IProduct。SimpleFactory有一定的逻辑处理功能,让用户使用起来更加方便

缺点:当要增加具体产品类是都要修改SimpleFactory类,有点违背了开放封闭原则--对扩展开放,修改封闭。

展望:简单工厂可以和抽象工厂+反射技术结合使用达到更好的高内聚低耦合效果,让封装更极致。

posted @ 2011-09-07 08:24  小虾Joe  阅读(333)  评论(0编辑  收藏  举报