有时,当您创建一个类时,您可以添加几个属性(新数据成员),如果您不想这样做,则不确定。例如,我有一个赌场老虎机游戏。我有瓷砖和瓷砖在不同的卷轴上旋转。所以一旦3个牌都出现在同一条线上,那么玩家将获得3 $,4个牌 - 4 $和5个牌 - $ $为牌A
和牌B
玩家赢$ 5,10 $,20相应的$。例如,每个瓷砖应该存储其奖励的数据,还是应该有一个奖励管理器,用于检查彼此相邻的多少个瓷砖是否给予玩家奖励?
请注意,我不想such a situation。但我发现我多次想到“我应该添加这些数据,因此,我的班级是否相应的逻辑?”。我担心single responsibility principle当我想要有不同的经理来做这些事情时,但另一方面我遇到了创建几个单身人士或类似单身人士的类的情况。
答案 0 :(得分:1)
嗯,这听起来很像Strategy Pattern的用例。
就我而言(从未到过赌场,因为他们在我的国家被禁止),大多数老虎机都以同样的方式工作。
因此,您可能会将一个实现视为(伪Java代码):
class Figure {
private String representation;
}
class Slot {
private Set<Figure> figures;
public Figure getRandom() {
// retrieve random figure from a slot
}
}
interface IRewardStrategy {
public int getReward(SlotMachine machine);
}
class OneFoldRewardStrategy implements IRewardStrategy {
public int getReward(SlotMachine machine) {
return machine.getCurrentLinedSlotsCount();
}
}
class TenFoldRewardStrategy implements IRewardStrategy {
public int getReward(SlotMachine machine) {
return 10 * machine.getCurrentLinedSlotsCount();
}
}
class SlotMachine {
private int slotCount;
private List<Slot> slots;
private List<Figure> currentRollResult;
private IRewardStrategy rs;
public SlotMachine(List<Slot> slots, IRewardStrategy rs) {
this.slots = slots;
this.rs = rs;
}
public void roll() {
// For each slot, get random figure
}
public int getTotalSlots() {
return slotCount;
}
public int getCurrentLinedSlotsCount() {
// Iterates over the current roll result and get the number of lined slots
}
public int getReward() {
this.rs.getReward(this); // delegates to the reward strategy
}
}
// Usage
SlotMachine machine = new SlotMachine(..., new TenFoldRewardStrategy());
machine.roll(); // suppose this give 3 slots in a row...
print(machine.getReward()); // This will yield 30
注意:这是一个非常简单的代码,只是为了给你一个想法,它有几个问题。