Factory Method模式

Factory Method模式可以由Template Method演变而来。用Template Method模式来构建生成实例的工厂,这就是Factory Method。

在Factory Method模式中,父类决定实例的生成方式,但是不决定具体要生成的类,具体的处理全部交给子类去负责。这样就可以将生成实例的框架(framework)和实际负责生成实例的类解耦。

类图

示例代码

Product(之定义抽象方法use的抽象类)

/**
 * 只定义抽象方法use的抽象类
 *
 * Created by xuefeihu on 18/4/12.
 */
public abstract class Product {

    public abstract void use();

}

Factory(实现了create方法的抽象类)

/**
 * 实现了create方法的抽象类
 *
 * Created by xuefeihu on 18/4/12.
 */
public abstract class Factory {

    public final Product create(String owner) {
        Product p = createProduct(owner);
        registerProduct(p);
        return p;
    }

    protected abstract Product createProduct(String owner);

    protected abstract void registerProduct(Product product);

}

IDCard(实现了use方法的类)

/**
 * 实现use方法的类
 *
 * Created by xuefeihu on 18/4/12.
 */
public class IDCard extends Product {

    private String owner;

    IDCard(String owner) {
        System.out.println("制作" + owner + "的ID卡.");
        this.owner = owner;
    }

    @Override
    public void use() {
        System.out.println("使用" + owner + "的ID卡.");
    }

    public String getOwner() {
        return owner;
    }

}

IDCardFactory(实现了createProduct、registerProduct方法的类)

/**
 * 实现了createProduct registerProduct方法的类
 *
 * Created by xuefeihu on 18/4/12.
 */
public class IDCardFactory extends Factory {

    private List owners = new ArrayList();

    @Override
    protected Product createProduct(String owner) {
        return new IDCard(owner);
    }

    @Override
    protected void registerProduct(Product product) {
        owners.add(((IDCard) product).getOwner());
    }

    public List getOwners() {
        return owners;
    }
}

Main(测试入口)

/**
 * 测试入口
 *
 * Created by xuefeihu on 18/4/12.
 */
public class Main {

    public static void main(String[] args) {
        Factory factory = new IDCardFactory();
        Product card1 = factory.create("小明");
        Product card2 = factory.create("小红");
        Product card3 = factory.create("小刚");
        card1.use();
        card2.use();
        card3.use();
    }

}


参考:《图解设计模式》