工厂方法是创建类设计模式(creational patterns)
中的一种常见设计模式。工厂模式又可以细分为简单工厂
、工厂方法
、抽象工厂
模式。
工厂模式的目标是:简化并封装对象创建过程,使得使用者只需要按需调用创建方法即可,而无需关注具体创建过程。
工厂模式中,涉及两个关键角色:工厂、产品。
简单工厂
该模式中,只有一个具体的工厂。工厂根据入参参数,返回不同的具体产品。
该模式的缺点是:如果要新增一个产品实现,就必须对工厂进行修改,这违反了设计模式中的开闭原则。
public abstract class Car {
}
public class BMW3Car extends Car {
}
public class BMW5Car extends Car {
}
public class BMWFacotry {
public Car createCar(int tpye) {
switch (tpye) {
case 3:
return new BMW3Car();
case 5:
return new BMW5Car();
default:
throw new UnsupportedOperationException();
}
}
}
public class App {
public static void main(String[] args) {
BMWFacotry bmwFacotry = new BMWFacotry();
bmwFacotry.createCar(3);
bmwFacotry.createCar(5);
}
}

工厂方法
为了解决简单工厂模式中的问题,工厂方法模式将工厂也进行抽象。不同的工厂实现,生产不同的产品。每个工厂只负责生产一种具体的产品
。这样如果需要新增一个产品生产,只需要新增一个工厂实现进行生产即可。
工厂方法可能引发的一个问题是,随着产品的增多,抽象工厂实现类的数量也会随之增加。
public abstract class AbstractBMWFacotry {
public abstract Car createCar();
}
public class BMW3Factory extends AbstractBMWFacotry {
public Car createCar() {
return new BMW3Car();
}
}
public class BMW5Factory extends AbstractBMWFacotry {
public Car createCar() {
return new BMW5Car();
}
}
public class App {
public static void main(String[] args) {
new BMW3Factory().createCar();
new BMW5Factory().createCar();
}
}

抽象工厂
抽象工厂和工厂方法模型基本一致,唯一的区别就是抽象工厂模式,一个工厂可以生产多种产品
,而工厂方法只生产一种产品。
public abstract class Car {
private Wheel wheel;
public void setWheel(Wheel wheel) {
this.wheel = wheel;
}
}
public class BMW3Car extends Car {
}
public class BMW5Car extends Car {
}
public abstract class AbstractBMWCombineFacotry {
public abstract Car createCar();
public abstract Wheel createWheel();
}
public class BMW3CombineFacotry extends AbstractBMWCombineFacotry {
public Car createCar() {
Car bmw3 = new BMW3Car();
bmw3.setWheel(createWheel());
return bmw3;
}
public Wheel createWheel() {
return new NormalWheel();
}
}
public class BMW5CombineFacotry extends AbstractBMWCombineFacotry {
public Car createCar() {
Car bmw5 = new BMW5Car();
bmw5.setWheel(createWheel());
return bmw5;
}
public Wheel createWheel() {
return new AdvancedWheel();
}
}
网友评论