Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

关于java工厂模式的作用?

看了很多文章都说工厂模式的作用是解耦,但是我还是不理解工厂模式new对象除了代码变代码变复杂了,看不有什么区别。

普通创建对象:

Car car = new Car();

工厂模式:

CarFactory carFactory = new CarFactory();
Car car = carFactory.getCar();
public class CarFactory(){
    public static Car getCar(){
        return new Car();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

一般来说,单个类的创建,是看不出工厂的优势的。看一个最常见的场景:

车有奔驰奥迪,传个司机进去就可以开了:

interface Car {
  void drive(Driver d);
}
class Benz implements Car {
    void drive(Driver d) { ... }
}
class Audi implements Car {
    void drive(Driver d) { ... }
}

创建的时候,对比一下:

Driver me = ...
Map<String, Object> data = Database.loadCar();
Car car;
if ("benz".equals(data.get("brand"))) {
    car = new Benz();
} else if ("audi".equals(data.get("brand"))) {
    car = new Audi();
} else {
    throw new RuntimeException("unknown brand");
}
car.drive(me);

Driver me = ...
Map<String, Object> data = Database.loadCar();
Car car = CarFactory.get(data);
car.drive(me);

后者的好处是,调用者根本不知道奔驰和奥迪的存在,如果要加入宝马保时捷路虎,这段代码也完全不需要修改,这满足了开闭原则(OCP对修改关闭,对扩展开放),同时也实现了OO的多态特性。

那加入宝马的时候是不是CarFactory的代码要改?是不是要新建Bmw类?是的。但是我们一般认为CarFactory是与Car在一起的,它不影响业务逻辑代码(想象CarCarFactory是放在一个第三方的库里的)。

要理解设计模式,最好是去理解OCP、LSP这些设计原则,然后忘记23种设计模式。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...