工厂方法factory method

    工厂的应用可以在数据库工厂,业务工厂等中经常能够看到。工厂方法是一种通用的构造器,可以产生不同的对象。你必须用一个静态方法,而不是一个构造函数来实现它。

A factory is a sort of generic constructor that might produce any of a number of different kinds of objects. You have to implement it as a static method rather than a constructor.

可以用下面的方式去实现一个工厂:

1)        switch语句来选择合适的构造函数。

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

3)        getInstance,并通过类名来创建任意对象。

You can implement a factory in several ways:

1)        Have a big switch and select the right constructor.

2)        Use a Hashtable/HashMap and .clone() to reproduce pre-initialized exemplar objects.

3)        Use getInstance to create arbitrary objects from just the class name provided as a String.

如果你想为其他人提供向工厂中添加新类型的能力,那么静态方法是个很好的选择。

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.

你也可以使用工厂在一个类中构造复杂的对象。

You can also use factories to build complicated objects of only a single class that must be built-in stages, when there are too many parameters to handle conveniently with a constructor. You want to avoid allowing any malformed or partly-formed objects loose out into the universe.

下面两个简单工厂的例子说明工厂的用处:

1)        创建控制。阻止无效对象的创建。如代码段一。

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

3)        自动对已经创建的对象进行后续处理。如代码段二。

Here is the code for two simple-minded factories, which illustrate some of the things factories are commonly used for:

1)        Birth control. Preventing the creation of invalid objects.

2)        Automatically creating specialized versions of objects.

3)        Automatic post processing of newly created objects.

代码段一:

代码段二:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值