我正在做一个RPG游戏,有一个Player
和一个Equipment
班。我应该在mountEquipment()
类中实现Player
方法,还是类似
public class Player {
private ArrayList<Equipment> equipments;
public void mountEquipment(Equipment e){
// how can i know what attributes
// Equipment will change in Player?
equipments.add(e);
}
}
或者我应该在Equipment
类中实现,该类将是
public class Equipment {
public void mountEquipment(Player p){
// here i can access all Player attributes
p.addStrength(50);
p.addHP(100);
p.addEquipment(this);
}
}
访问Player
类中定义mountEquipment
的{{1}}属性比较容易,但是我认为在Equipment
类中使用mountEquipment
更有意义很难更改Player
属性。例如,Player
可以改变力量,Sword
可以改变力量和运气。
在这种情况下,我应该在哪里实现此类?
答案 0 :(得分:1)
在简单的情况下,玩家的数据基本上只是其基本数据+装备数据的总和。
似乎是共享界面的机会:
public interface StatProvider {
int health();
int intellect();
}
public class Ring implements StatProvider {
@Override
public int health() {
return 0;
}
@Override
public int intellect() {
return 5;
}
}
public class Mage implements StatProvider {
private final int baseHealth = 100;
private final int baseIntellect = 20;
private List<StatProvider> equipment;
@Override
public int health() {
return baseHealth + equipment.stream().mapToInt(StatProvider::health).sum();
}
@Override
public int intellect() {
return baseIntellect + equipment.stream().mapToInt(StatProvider::intellect).sum();
}
}
也许也可以与装饰器模式配合使用
public class HealthDoublingEnchantment implements StatProvider {
private final StatProvider delegate;
public HealthDoublingEnchantment(StatProvider delegate) {
this.delegate = delegate;
}
@Override
public int health() {
return delegate.health() * 2;
}
@Override
public int intellect() {
return delegate.intellect();
}
}
例如
new HealthDoublingEnchantment(new Ring());