简单工厂模式

2018-10-26  本文已影响2人  juconcurrent

概念

简单工厂是只有一个工厂,却能生产多种产品的模式。那工厂里面如何判断应该生产哪种产品呢?这个条件就由生产方法的入参传入的啦。

示例

public interface Car {
}
public class Jeep implements Car {
}
public class Porsche implements Car {
}

public class Producer {

    public Car produce(int type) {
        if (type == 1) {
            return new Jeep();
        } else if (type == 2) {
            return new Porsche();
        } else {
            throw new UnsupportedOperationException("unsupported type input!");
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读