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();
    }
}

猜你喜欢

转载自blog.csdn.net/tmaczt/article/details/82722161