【问题标题】:How to apply Bridge Design pattern if the implementor must know exactly which abstraction to implement?如果实现者必须确切知道要实现哪个抽象,如何应用桥接设计模式?
【发布时间】:2018-04-20 13:46:49
【问题描述】:

我有一个必须实现 Player 和 Mode 的游戏项目。 Player 类有两个子类HumanPlayerBotPlayer,Mode 类有两种模式:简单模式和困难模式。

这是我的类图:

人类玩家和机器人将具有“初始化武器”功能。对于简单模式,人类玩家将拥有各种武器,而机器人玩家将只有有限数量的武器。那么如果我像上图那样实现桥接模式,我怎么知道在Easy模式下是哪个抽象(玩家或机器人)来实现“初始化武器”功能?

【问题讨论】:

标签: java


【解决方案1】:

在开始游戏之前将武器交给玩家。所以不是玩家对象知道它拥有哪些武器,而是游戏(或游戏模式)知道武器。

有很多方法可以做到这一点,但作为一个例子:

public abstract class Mode {
  public abstract Collection<Weapon> getHumanWeapons();
  public abstract CollectionWeapon> getBotWeapons();
}

public class Easy extends Mode{
  public Collection<Weapon> getHumanWeapons() {
         return Collections.singleton(new NukeBlaster()));
  }

  public Collection<Weapon> getBotWeapons() {
         return Collections.singleton(new Flower()));
  }
}


public HumanPlayer(Mode mode) {
   this.weapons = mode.getHumanWeapons(); 
}

public BotPlayer(Mode mode) {
   this.weapons = mode.getBotWeapons();
}

或者...让Mode 返回一个HumanConfiguration 和一个BotConfiguration,这反过来又提供了武器和行为。这将为Player 类提供一个构造函数,并确保机器人不会偷窃人类武器。

public abstract class Mode {
    public abstract Configuraton getHumanConfiguration();
    public abstract Configuraton getBotConfiguration();
}

public class Configuration {
    public Collection<Weapon> getWeapons() { ... }
}

public class Player {
    private Collection<Weapon> weapons;

    public Player(Configuration configuration) {
       this.weapons = configuration.getWeapons(); 
    }
}

【讨论】:

    猜你喜欢
    • 2016-05-06
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    相关资源
    最近更新 更多