gpt4 book ai didi

java - 用模式设计风格的抽象方法定义抽象类

转载 作者:行者123 更新时间:2023-12-02 07:51:36 25 4
gpt4 key购买 nike

如何使用设计模式在抽象类中定义抽象方法,同时可以覆盖或更改其在子类中的行为?在此示例中,公共(public)抽象类 GameCharacter 具有方法 attack,该方法应该类似于模式(在 GameCharacter 中定义一些方法,有些留空,在子类中被*覆盖*)。

public abstract class GameCharacter{

public void attack(GameCharacter opponent){

while(opponent.hitPoints > 0 && this.hitPoints > 0){

// some abstract method which behavior can be *redefined*
//if specific class is *overrides*
// some of this functions
// it should be pattern design

public void doDamageToOpponent{

doAttackOne(){ .... }; // cannot change
doAttackTwo(); // can change, be overridden in child class

}

public void doDamageToThis{ // counterattack

doAttackOne(){ .... }; // cannot change
doAttackTwo(); // can change, be overriden in child class

}

}

最佳答案

我猜你想要的是这样的:

public abstract class GameCharacter{

protected abstract doAttackTwo();

protected final doAttackOne() { ... implement here ... }

...
}

doAttackTwo() 必须由子类实现,而 doAttackOne() 不能被覆盖。

关于java - 用模式设计风格的抽象方法定义抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10162084/

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