/**
* @author:xusonglin
* ===============================
* Created with IDEA.
* Date:2019/1/3
* Time:20:51
* role:创建者 (Creator)
* action:决定实例的创建方式
* ================================
*/
public abstract class Factory {
public final Product create(String owner){
Product product = createProduct(owner);
registerProduct(product);
return product;
}
protected abstract Product createProduct(String owner);
protected abstract void registerProduct(Product product);
}
**
* @author:xusonglin
* ===============================
* Created with IDEA.
* Date:2019/1/3
* Time:20:52
* role: 产品 (Product)
* action: 实例所持有的接口(API)
* ================================
*/
public abstract class Product {
public abstract void use();
}
/**
* @author:xusonglin
* ===============================
* Created with IDEA.
* Date:2019/1/3
* Time:20:53
* role: 具体的创建者(ConcreteCreator)
* action: 具体加工的一方,负责生产具体的产品
* ================================
*/
public class IdcardFactory extends Factory {
private List<String> owners = new ArrayList();
protected Product createProduct(String owner) {
return new Idcard(owner);
}
protected void registerProduct(Product product) {
owners.add(((Idcard)product).getOwner());
}
public List<String> getOwners() {
return owners;
}
}
/**
* @author:xusonglin
* ===============================
* Created with IDEA.
* Date:2019/1/3
* Time:20:53
* 具体产品
* ================================
*/
public class Idcard extends Product {
private String owner;
public Idcard(String owner) {
System.out.println("制作 " +owner +" 的Id卡。");
this.owner = owner;
}
public void use() {
System.out.println("使用 " +owner +" 的Id卡。");
}
public String getOwner() {
return owner;
}
}
/**
* @author:xusonglin
* ===============================
* Created with IDEA.
* Date:2019/1/3
* Time:21:09
* ================================
*/
public class FactoryMethodTest {
public static void main(String[] args){
Factory factory = new IdcardFactory();
Product product1 = factory.create("一号");
Product product2 = factory.create("二号");
Product product3 = factory.create("三号");
product1.use();
product2.use();
product3.use();
}
}
制作 一号 的Id卡。
制作 二号 的Id卡。
制作 三号 的Id卡。
使用 一号 的Id卡。
使用 二号 的Id卡。
使用 三号 的Id卡。