少数民族游戏中的代理:继承层次结构,通过接口或某些模式的可插拔行为?

时间:2010-01-23 15:42:20

标签: design-patterns architecture inheritance oop interface

我目前正在建立一个图书馆,以便模拟各种不同的少数民族游戏。这涉及代理在两个选项之间进行选择,例如A和B,因此代理的主要功能是选择。如果代理人在所有代理人选择之后最终进入少数群体,则代理人会赢得游戏中的转折点。

显然,有许多不同的方式可以让代理人做出选择,而游戏则会调查不同选择制定策略对系统整体财富的影响。我需要代理商能够选择的一些方式是:

  • 完全随意
  • 通过提供内存,以便他们能够记住过去的m个少数选择,并将此内存用作策略映射到少数选择预测的输入
  • 通过预测并将其公布给代理商的“朋友”,然后每个代理商根据某些条件选择是否信任其朋友。

现在出现编程问题。我目前有一个AbstractAgent,它封装了所有这些功能。事情是某些类型的代理商没有朋友列表,一组策略或记忆等。目前所有这些能力都堵塞了基类。我可以使用继承层次结构,但我认为层次结构中的不同类之间会有交叉,即有时代理可能有朋友和策略,有时候只有朋友或策略。同样,我可以有一个接口集合,每个不同的代理实现它需要的任何接口,即

public enum Choice {
    A, B
}

public interface Decidable {
    private Choice choice;
    public Choice getChoice();
    public void choose();
}

public interface Strategic {
    private StrategyManager strategies;
    public StrategyManager getStrategyManager;
    public void setStrategyManager(StrategyManager strategyManager);
}

public class CleverAgent implements Decidable, Strategic {
    // decides more intelligently using the strategies
}

public class StupidAgent implements Decidable{
    public void choose() {
        if(Math.random < 0.5) {
            return Choice.A
        } else {
            return Choice.B
        }
    }
}

现在,如果我走这条路,我已经可以看到许多界面,如战略,可判断,可评价,有状态,难忘和可交换。我觉得实际的解决方案应该是继承层次结构之间的混合(我至少知道所有代理都是Decidable,因此应该放在基类中)与可插拔行为相结合。

我的问题是这种情况下最好的方法是什么?我应该研究一下设计模式吗?每种方法的优点和缺点是什么,尤其是它如何影响库中的其他代码,因为需要在整个游戏中为实验目的调查代理状态?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我认为使用Strategy模式会对您的情况有所帮助。您可以拥有一个抽象基类(比如代理)并提供用于设置行为的setter,或者可以在构造函数中设置行为。

以下是一些示例代码来解释我的意图:

abstract class Agent {
    Strategic strategy;
    Decidable chooser;

    public setStrategy(Strategic s) {
        this.strategy = s;
    }

    public setChoiceMaker(Decidable c) {
         this.choser = c;
    }

    abstract public void action();
}

class IntelligentAgent extends Agent {
    public void action() {
        // perform some action by invoking methods in 
        // interface Strategic and Decidable 
    }
 }

class StupidtAgent extends Agent { 
    public void action() {
        // for stupid agent you can set strategy and choice
        // to refer to some suboptimal implementations of 
        // Strategic and Decidable
    }
}

abstract class Agent { Strategic strategy; Decidable chooser; public setStrategy(Strategic s) { this.strategy = s; } public setChoiceMaker(Decidable c) { this.choser = c; } abstract public void action(); } class IntelligentAgent extends Agent { public void action() { // perform some action by invoking methods in // interface Strategic and Decidable } } class StupidtAgent extends Agent { public void action() { // for stupid agent you can set strategy and choice // to refer to some suboptimal implementations of // Strategic and Decidable } }

策略模式带来的优势是代理的行为现在由合成决定,必要时可以修改(通过提供设置者)。