简单工厂模式

简单工厂模式是类的创建模式,又叫做静态工厂方法模式。

简单工厂模式不能说是一个设计模式,说它是一种编程习惯可能更恰当些。因为它至少不是Gof23种设计模式之一。但它在实际的编程中经常被用到,而且思想也非常简单,可以说是工厂方法模式的一个引导

就是由一个工厂类根据传入的参量决定创建出哪一种产品类的实例。一般涉及到三种角色:

工厂类:担任这个角色的是工厂方法模式的核心,含有与应用紧密相关的商业逻辑。工厂类在客户端的直接调用下创建产品对象,它往往由一个具体的类实现。

抽象产品角色:担任这个角色的类是由工厂方法模式所创建的对象的父类,或她们共同拥有的接口。一般由接口或抽象类实现。 

具体产品角色:工厂方法模式所创建的任何对  象都是这个角色的实例,由具体类实现。

以园丁种植水果为例讨论该模式的具体实现:  Fruit 水果接口,规定水果具有的一些共同特性  Apple 苹果类 派生自Fruit接口  Strawberry 草莓类 派生自Fruit接口  FruitGardener 园丁类 负责草莓与苹果的创建工作。  当Client要创建水果(苹果或草莓对象)的时候调用园丁类的factory

public interface Fruit  
{  
    void grow();  
    void harvest(); 
    void plant();  
} 
public class Apple:Fruit 
{ 
    public Apple() 
    { 
    } 
    #region Fruit 成员 
    public void grow() 
    { 
        Console.WriteLine ("Apple is growing......."); 
    } 
    public void harvest() 
    { 
        Console.WriteLine ("Apple is harvesting......."); 
    } 
    public void plant() 
    { 
        Console.WriteLine ("Apple is planting......."); 
    } 
    #endregion 
public class Strawberry:Fruit 
        { 
            public Strawberry() { } 
            #region Fruit 成员 
            public void grow() 
            { 
                Console.WriteLine ("Strawberry is growing......."); 
            } 
            public void harvest() 
            { 
                Console.WriteLine ("Strawberry is harvesting......."); 
            } 
            public void plant() 
            { 
                Console.WriteLine ("Strawberry is planting.......");
            } 
            #endregion 
    public class FruitGardener 
    { 
        //静态工厂方法 
        public static Fruit factory(string which) 
        { 
            if(which.Equals ("Apple")) 
            {
                return new Apple(); 
            } 
            else if(which.Equals ("Strawberry")) 
            { 
                return new Strawberry (); 
            } 
            else { return null; } 
        } 
    }
    class Client 
    {
        [STAThread] 
        static void Main(string[] args) 
        { 
            Fruit aFruit=FruitGardener.factory ("Apple");//creat apple 
            aFruit.grow (); 
            aFruit.harvest (); 
            aFruit.plant(); 
            aFruit=FruitGardener.factory ("Strawberry");//creat strawberry
            aFruit.grow (); 
            aFruit.harvest (); 
            aFruit.plant(); 
        } 
    } 

输出如下: 
Apple is growing....... 
Apple is harvesting....... 
Apple is planting....... 
Strawberry is growing....... 
Strawberry is harvesting....... 
Strawberry is planting....... 

 

总结:

创建一个抽象工厂,它决定返回哪一个类的实例并将该实例返回。接下来可以调用那个类实例的方法,但不需要知道具体使用的是哪一个子类,这种方法把和数据相关的问题与类的其他方法分隔开来。它能返回具有同样方法的类的实例,它们可以是不同的派生子类的实例,也可以是实际上毫无关系仅仅是共享了相同接口的类。不管哪一种类实例中的方法必须是相同的,并且能够被交替使用。

posted @ 2013-02-21 10:11  xiepeixing  阅读(250)  评论(0编辑  收藏  举报