通过分析Spring源码解析设计模式的使用方法。下面看一个例子:
这里创建对象的接口是WebServer,其实现类TomcatWebServer、JettyWebServer、NettyWebServer,抽象工厂类是ServletWebServerFactory,其实现类包括JettyServletWebServerFactory、TomcatServletWebServerFactory、UndertowServletWebServerFactory。
1. 优点
- 降低了耦合度,不用把对象实例化的复杂过程在具体调用的地方进行组装设值。
- 提供了扩展性,在新增加对象时,可通过增加具体工厂类和具体实现类来完成。
- 提高了封装性,针对外部调用获取该类的实例化时,通过统一的工厂方法调用,不用关心实例化过程,使代码更简洁,达到了职责分离的目的。
2. 缺点
- 会产生额外的工厂类,当实现类较多时,会产生大量的工厂类数量,增加了代码量。
- 会增加代码的复杂度,对于代码经验较少的coder会增加理解难度。
3. 测试例子
public interface Fruit {
BigDecimal getWeight();
String getName();
}
@NoArgsConstructor
@AllArgsConstructor
public class Apple implements Fruit {
private BigDecimal weight;
private String name;
@Override
public BigDecimal getWeight() {
return this.weight;
}
@Override
public String getName() {
return this.name;
}
}
@NoArgsConstructor
@AllArgsConstructor
public class Orange implements Fruit {
private BigDecimal weight;
private String name;
@Override
public BigDecimal getWeight() {
return this.weight;
}
@Override
public String getName() {
return this.name;
}
}
public interface TreeFacotry {
Fruit produce();
}
public class AppleTreeFactory implements TreeFacotry {
@Override
public Fruit produce() {
return new Apple(new BigDecimal("1.4"), "苹果");
}
}
public class OrangeTreeFactory implements TreeFacotry {
@Override
public Fruit produce() {
Orange orange = new Orange(new BigDecimal("2.3"), "橘子");
return orange;
}
}
public class FruitDemo {
public static void main(String[] args) {
TreeFacotry appleTreeFactory = new AppleTreeFactory();
Fruit apple = appleTreeFactory.produce();
System.out.println("apple weight: " + apple.getWeight() + ", apple name: " + apple.getName());
TreeFacotry orangeTreeFactory = new OrangeTreeFactory();
Fruit orange = orangeTreeFactory.produce();
System.out.println("orange weight: " + orange.getWeight() + ", orange name: " + orange.getName());
}
}
打印效果如下: