gpt4 book ai didi

java - 模板模式,但其中一个类未实现该方法

转载 作者:行者123 更新时间:2023-12-01 07:45:10 25 4
gpt4 key购买 nike

我正在尝试实现模板方法模式,但我需要一些细微的变化,我认为这不是最佳实践。我有以下类结构

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
}
}

在实际情况中,我有大约 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
}
}

关于java - 模板模式,但其中一个类未实现该方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54554346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com