我有一些非常相似的功能,但每一个功能都有一条线是不同的。这种情况的最佳解决方案(设计模式)是什么?
我该如何避免代码重复?
public class Example{
public void f(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct1(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
public void g(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct2(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
public void h(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct3(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
public void i(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct4(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
}
你能告诉我一些合适的设计模式吗?
我会看看到[模板方法模式(http://en.wikipedia.org/wiki/Template_method_pattern)。 – rgettman 2014-09-19 17:54:07
有抽象父类吗? – user2693979 2014-09-19 17:57:33
你能多给一点背景吗?这是更多的仪器,或方法装饰? – 2014-09-19 18:17:41