Java 设计模式_工厂模式

Java 设计模式_工厂模式


本文由 Luzhuo 编写,转发请保留该信息.
原文: http://blog.csdn.net/rozol/article/details/76060105


通过一个工厂类帮你创建对象
工厂模式分为: 工厂类模式 / 抽象工厂模式

提前定义的bean类

// Car.java
public class Car implements Product{
    public Car() {}

    @Override
    public void run(){
        System.out.println("The car is running.");
    }
}
// Bicycle .java
public class Bicycle implements Product {
    public Bicycle() {}

    @Override
    public void run(){
        System.out.println("The bicycle is running.");
    }
}
// Product.java
public interface Product {
    void run();
}

工厂类模式

public class 工厂类 { //工厂类
    public 工厂类() {}

    public static Product getInstance(String type){
        switch (type) {
        case "Car":
            return new Car();
        case "Bicycle":
            return new Bicycle();
        default:
            throw new IllegalArgumentException();
        }
    }
}
  • 接受参数, 根据参数来决定返回实现同一接口的不同类的实例

抽象工厂模式

public interface Factory {
    public Car getCar(); 
    public Bicycle getBicycle();
}
public class TransportFactory implements Factory{
    @Override
    public Car getCar(){
        return new Car();
    }

    @Override
    public Bicycle getBicycle(){
        return new Bicycle();
    }
}
  • 对产品进行分类
  • (产品的分类是抽象工厂的重点), 用于创建一系列产品

使用

public class Test {
    public static void main(String[] args) {

        // 工厂类
        工厂类();

        // 抽象工厂
        抽象工厂();
    }

    private static void 工厂类() {
        Product car = 工厂类.getInstance("Car");
        Product bicycle = 工厂类.getInstance("Bicycle");

        car.run();
        bicycle.run();
    }

    /**
     * (产品的分类是抽象工厂的重点), 用于创建一系列产品
     */
    private static void 抽象工厂() {
        Factory transport = new TransportFactory();

        Car car = transport.getCar();
        Bicycle bicycle = transport.getBicycle();

        car.run();
        bicycle.run();
    }
}

你可能感兴趣的:(java)