定义
定义一个用于创建对象的接口,让子类决定实例化哪个类
使用场景
在任何需要生成复杂对象的地方,都可以使用工厂模式
UML类图
上面是抽象接口类的结构层次,下面我们用网络套餐举例
Meal.java
public abstract class Meal {
private User user;
private String name;
private float price;
public abstract void method();
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
CommonMeal.java
public class CommonMeal extends Meal{
@Override
public void method() {
System.out.print("普通套餐");
}
}
SpeedMeal.java
public class SpeedMeal extends Meal {
@Override
public void method() {
System.out.print("高速套餐");
}
}
Factory.java
public abstract class Factory <T extends Meal>{
public abstract T createMeal();
}
CommonFactory.java
public class CommonFactory extends Factory<CommonMeal>{
@Override
public CommonMeal createMeal() {
CommonMeal meal = new CommonMeal();
meal.setName("xxx");
meal.setPrice(20f);
User user = new User();
user.setSerial("xxx");
meal.setUser(user);
return meal;
}
}
SpeedFactory.java
public class SpeedFactory extends Factory<SpeedMeal> {
@Override
public SpeedMeal createMeal() {
SpeedMeal meal = new SpeedMeal();
meal.setName("xxx");
meal.setPrice(30f);
User user = new User();
user.setSerial("xxx");
meal.setUser(user);
return meal;
}
}
调用
//生成普通套餐
CommonFactory commonFactory = new CommonFactory();
CommonMeal commonMeal = commonFactory.createMeal();
//生成高速套餐
SpeedFactory speedFactory = new SpeedFactory();
SpeedMeal speedMeal = speedFactory.createMeal();
总结
优点
- 降低了对象之间的耦合度
- 代码结构清晰,对调用者隐藏了产品的生产过程,生产过程改变后,调用者不用做什么改变,易于修改
- 易于拓展,要增加工厂和产品都非常方便,直接实现接口,不用修改之前的代码。
缺点
增加代码结构层次,如果是简单的new就可以得到对象不建议用工厂模式