D.T*_*mov 0 java oop design-patterns
我正在尝试实现模板方法模式,但我需要一些细微的变化,我认为这不是最佳实践。我有以下课程结构
abstract class AbsClass {
public void algorithm(){
step1();
step2();
}
private void step1() {
//implementation
}
protected abstract void step2();
}
class A extends AbsClass {
protected void step2() {
// With implementation
}
}
class B extends AbsClass {
protected void step2() {
// No implementation needed
}
}
Run Code Online (Sandbox Code Playgroud)
在实际情况中,我有大约 4 个类,其中一个类不需要实现第二步。我认为将方法留空并不是一个好的做法。我想在其中添加评论(说不需要实施),但我认为这不是正确的解决方案。还有另一种我没有看到的方法吗?
我们不应该强制采用一种设计模式。在这里,如果我们更喜欢组合而不是继承,那就更好了。
问题中的代码我们在类中定义了一个方法,但实际上方法没有行为。在一个不应该属于的类中强制使用一个方法并不是一个好主意。
下面是一种可能的实现,如果某个方法不属于某个类,则不会强制该方法使用该类。下面是基于策略模式,但我仍然想说遵循设计原则,让模式本身适合您的问题,而不是强迫模式适合您的解决方案。
public class AlgorithmClass {
private Strategy strategy;
public void setStrategy(Strategy strategy){
this.strategy = strategy;
}
public void algorithm(){
step1();
step2();
}
private void step1() {
//implementation
}
private void step2(){
if(this.strategy != null){
this.strategy.execute();
}
}
}
public interface Strategy{
public void execute();
}
public class Strategy1 implements Strategy{
public void execute(){
//implement your one of the stategies for step 2
}
}
public class Strategy2 implements Strategy{
public void execute(){
//implement your another stategy for step 2
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1211 次 |
| 最近记录: |