现在的位置: 首页 > 综合 > 正文

工厂方法——Factory Method

2017年12月22日 ⁄ 综合 ⁄ 共 751字 ⁄ 字号 评论关闭

工厂方法是一个能够返回实例对象的静态方法,在JDK中有以下几个例子使用到:

LogManager.getLogManager

Pattern.compile

Calendar.getInstance 

工厂方法的好处:

1.具有名字,使得代码更优雅,不像构造器。

2.不一定每次都产生一个新的对象,如果必要的话,原来的对象可以被存储。

3.可以返回定义类型的子类对象。尤其是可以返回实现了定义接口但对调用者来说未知 的一个类(这个类implements 一个interface,但是个什么样的类,对调用者来说是未知的)。因此,框架往往用interface来作为工厂方法的返回类型。

一般的方法名称为,getInstance 和 valueOf。

Example:

public final class ComplexNumber {
    private float fReal;
    private float fImaginary;
    /**
     * Static factory method returns an object of this class.
     */
    public static ComplexNumber valueOf(float aReal, float aImaginary) {
        return new ComplexNumber(aReal, aImaginary);
    }

    /**
     * Caller cannot see this private constructor.
     *
     * The only way to build a ComplexNumber is by calling the static
     * factory method.
     */
    private ComplexNumber(float aReal, float aImaginary) {
        fReal = aReal;
        fImaginary = aImaginary;
    }
    //..elided
} 

抱歉!评论已关闭.