Execute Around方法和模板模式之间的区别

时间:2017-04-03 06:39:47

标签: java design-patterns java-8

我试图使用Java 8 Lambdas实现一些GoF设计模式。在本练习中,我遇到了Execute Around Method(EAM)模式和模板模式。两者似乎都有惊人的相似之处。

我已经读过EAM更像是一个没有继承的习惯用法,与使用继承的模板模式相比,大多数例子似乎都在处理资源(open,doSomething,close)。

在进一步阅读时,我发现EAM似乎在Smalltalk中有历史。

但是,使用Java 8 Lambdas,我们实际上可以摆脱模板模式中的继承并简单地传递行为。实现EAM习语的解决方案与模板设计模式非常相似。可以查看open,doSomething,close作为Template模式,open()和close()是相同的步骤但doSomething()是子类。使用Java 8 Lambdas,我们可以简单地将doSomething的行为传递给接受java.util.function.Consumer的函数。这可以看作是EAM和模板模式。

所以我的问题是两者有什么区别?

1 个答案:

答案 0 :(得分:2)

在GoF设计模式中,EAM更像是Strategy Pattern。 战略与战略Template Method模式都是基于算法的行为模式,但它们有点不同。

在类中定义为模板方法模式的步骤在运行时无法替换其中一个,如果需要,必须用另一个子类实例替换整个实例,但使用策略模式可以将其替换为另一个策略实例。

策略模式更像是将每个步骤分成单独的策略类型,模板方法将算法分解为步骤并将步骤推迟到子类。但有时候是通过模板方法实现的策略类型。例如:

策略方法

Runnable step1 = ()->{};
Runnable step2 = ()->{};
Runnable step3 = ()->{};

play(step1,step2);
play(step3,step2); //replace step1 with step3

模板方法

class TemplateMethod{
  void run(){
    step1();
    step2();
  }

  void step1(){}
  void step2(){}
}

class Foo extends TemplateMethod{
  void step1(){
      System.out.println("foo");
  }
}

class Bar extends TemplateMethod{
  void step1(){
      System.out.println("foo");
  }
}


TemplateMethod foo=new Foo();
TemplateMethod bar=new Bar(); 

play(foo);
play(bar);// you must replace steps with another subclass instance