1. 程式人生 > >Java 抽象工廠模式

Java 抽象工廠模式

定義:為建立一組相關或相互依賴的物件提供一個介面,而且無需指定具體類。

抽象產品類:

public abstract class Product {
    /**
     * 公共方法
     */
    public void common() {
        System.out.println("公共方法");
    }

    public abstract void detail();
}

產品實現類:

public class Car extends Product {
    @Override
    public void detail() {
        System.out.println("汽車"
); } } public class Plane extends Product { @Override public void detail() { System.out.println("飛機"); } }

抽象工廠介面:

public interface Creator {
    Product createCar();

    Product createPlane();

}

抽象工廠實現類:

public class CreatorImpl implements Creator {
    @Override
    public
Product createCar() { return new Car(); } @Override public Product createPlane() { return new Plane(); } }

測試示例:

public class Example {
    public static void main(String[] args) {
        Creator creator = new CreatorImpl();
        Product product = creator.createCar();
        product.detail();
        product = creator.createPlane();
        product.detail();
        product.common();
    }
}