1. 程式人生 > >設計模式(一):Factory Method

設計模式(一):Factory Method

/**
 * @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卡。