目录
这次我们利用模板模式固定下策略模式的骨架,工厂模式提供注册策略,获取策略的方法,提供一个三个设计模式的例子。
java
abstract class Template{
// 模板方法,定义了算法的骨架
public void templateMethod() {
System.out.println("执行模板方法的前置操作");
Product product = createProduct();
System.out.Printlin(product.toString);
System.out.println("执行模板方法的后置操作");
}
// 工厂方法,由子类实现具体的产品创建
protected abstract Product createProduct();
}
// 具体策略类1/子模板1
class StrategyImpl1 extends Template {
@Override
protected Product createProduct() {
return "产品1";
}
@PostConstruct
public void registryFactory(){
Factory.CHOOSER_MAP.registry("1",this);
}
}
// 具体策略类2/子模板2
class StrategyImpl2 extends Template {
@Override
protected Product createProduct() {
return "产品2";
}
@PostConstruct
public void registryFactory(){
Factory.CHOOSER_MAP.registry("2",this);
}
}
// 工厂接口
public class Factory {
private final static Map<String, Strategy > CHOOSER_MAP = new ConcurrentHashMap<>();
public static void registry(String code, Strategy strategy ) {
CHOOSER_MAP.put(code, strategy );
}
public static Strategy chose(String code) {
CHOOSER_MAP.get(code);
}
}
// 测试类
public class Main {
public static void main(String[] args) {
StrategyImpl1 StrategyImpl1 = PlatformChooserFactory.chose("1");
StrategyImpl1.templateMethod();
StrategyImp2 StrategyImpl2 = PlatformChooserFactory.chose("2");
StrategyImpl2.templateMethod();
}
}
优缺点
- 灵活性:策略模式允许在运行时选择不同的策略,工厂模式可以根据需求创建相应的对象,模板模式定义了算法的骨架。这种组合可以使系统更加灵活,能够根据不同的需求选择合适的策略、对象和算法。
- 可扩展性:通过工厂模式,可以轻松添加新的具体产品,通过策略模式,可以添加新的策略,通过模板模式,可以添加新的算法实现。这使得系统更容易扩展,可以根据需要动态添加新的产品、策略和算法。
- 代码复用:策略模式、工厂模式和模板模式都鼓励代码的重用。策略模式中的策略、工厂模式中的产品和模板模式中的模板方法可以在不同的上下文中被重复使用,避免了重复编写相似的代码。
- 松耦合:策略模式、工厂模式和模板模式的结合可以实现松耦合的设计。策略模式通过接口与具体策略解耦,工厂模式通过抽象工厂与具体产品解耦,模板模式通过模板方法与具体算法解耦。这种松耦合设计使得系统更加灵活、可维护和可测试。
缺点:
- 增加复杂性:使用策略模式、工厂模式和模板模式的混合会增加代码的复杂性,需要定义多个接口、类和实现。这可能会增加开发和维护的成本。
- 增加类的数量:使用策略模式、工厂模式和模板模式的混合可能导致类的数量增加,特别是在有多个具体策略、产品和算法时。这可能会增加系统的复杂性和内存占用。
总结
需要根据具体的应用场景和需求来权衡使用策略模式、工厂模式和模板模式的混合。在某些情况下,这种组合可以提供更灵活、可扩展和可维护的设计,但也需要考虑代码复杂性和类的数量增加的影响。