工厂方法(factory method)

本文内容

  • 实现工厂方法
  • 工厂方法作用

 

工厂是一种通用的构造函数,用来创建任何不同的对象。你必须用一个静态方法来实现工厂,而不能用一般的构造函数。

工厂可以应用在数据库工厂或是业务工厂,等等。

 

实现工厂方法

你可以用很多方式来实现一个工厂:

1)  用一个 switch 语句(也许很大、很多的 case),来选择合适的构造函数。

2)  用 Hashtable/HashMa p和 .clone(),来复制一个已经被预初始化的样例对象。

3)  用 getInstance,通过类名创建任意对象。该方法将类的构造函数访问属性设置为 private,并

在该类中添加 getInstance 静态方法,访问属性为 public static,在此方法创建类的实例。

如果你想为其他开发人员提供向工厂添加新类型的功能,那么,静态方法是个很好的选择。你不能直接重构一个静态的工厂方法,其他人会忽略一个重构的实例的工厂方法。(If you want to give others the ability to add new types to the factory, the static method pretty well has to fob the work off on a factory delegate object or objects that can be changed. You can’t directly override a static factory method, and others would ignore an overridden instance factory method.)

当创建一个对象,需要太多参数时,你可以只用一个类,使用工厂生成复杂的对象。这样就可以避免任何形式的松散。

 

工厂方法作用

下面两个例子,说明工厂的优点:

1)  生成控制。阻止无效对象的创建。

/// <summary>
/// Factory to avoid even allocating any RAM for malformed objects.
/// factory to create Integer objects only for 1 to 100
/// </summary>
/// <param name="anInt">an integer 1..100</param>
/// <returns>the corresponding Integer object. If anInt is out of range, it returns null.</returns>
public static object smallIntegerFactory(int anInt)
{    
    if (1 <= anInt && anInt <= 100)    
    {                
        return  (object)anInt;    
    }    
    else    
    {        
        return null;    
    }
}

 

2)  自动创建指定版本的对象。

3)  自动对已经创建的对象进行后续处理。

/// <summary>
/// Factory to create both Dalmation AND Dog objects.
/// The Dalmatian constructor is private, so you can't call it directly.
/// This method forces users to register every Dalmatian object they produce.
/// </summary>
/// <param name="spots">count of spots</param>
/// <returns></returns>
public static Dog createDog(int spots)
{    
    Dog d;    
    if (spots > 0)    
    {        
        // The factory CAN call the private constructor, but other classes cannot.        
        d = new Dalmatian(spots);    
    }    
    else if (spots == 0)    
    {        
        d = new Dog();    
    }    
    else    
    {        
        return null;    
    }    
    // enforce some processing on every newly created object.    
    register(d);    
    d.getShots();    
    kennel.add(d);    
    return d;
}
 
 

下载 Demo

posted @ 2011-09-04 20:04  船长&CAP  阅读(427)  评论(0编辑  收藏  举报
免费流量统计软件