对于这个问题稍微有点疯狂的措辞感到抱歉,但我对面向代理的思维(这些'模式'是什么?)非常陌生,并且对Java来说只是稍微不那么新,而且我正在努力想到这个问题。非常基本的问题。
我正在做很多'直觉'(即盲目地),而不是试图理解别人的代码 - 部分是因为我很难理解“高于我的水平”的代码,但也因为我希望这样做'我的方式'将帮助我以后正确的方式欣赏。
基本上,我在一个环境(房子)中建模代理(机器人真空)。 A House包含Rooms的集合(HashMap)。 House有一个方法getRoom(int key)
,它返回与给定键匹配的Room。代理人有一个国家,在这一点上跟踪房间ID(这也是众议院的关键),这是机器人为了导航世界而进入的房间;一个州还描述了房间是否脏了。构建代理程序时,它使用ID初始化(必须在“房间”中创建),但不会给出房间的脏/清洁状态。我希望代理检查污垢 - 这将涉及在House中调用getRoom()
方法。但是,到目前为止我学到的Java,我不知道如何做到这一点。我知道我可以通过在java中创建一个House来访问该方法,或者通过使该方法保持静态,但这些方法不起作用 - 代理需要知道内存中的SPECIFIC房屋,已经初始化为房间的房屋
tl; dr:Agent对象如何获取对存储在另一个Environment对象中的HashMap中的对象的引用?
P.S这是我通过这种方法实现的“更高层次”观点的想象模型: 我有点直觉地希望代理对自己的规则和行为负全部责任,以便更高的代码看起来更像:
agent.percieve() //agent checks the room it thinks its in for dirt and exits
if (agent.gotDirt()) agent.clean() //agent activates its cleaning device if it found dirt in this room
if (agent.gotDirt() == false) agent.move() //agent picks an exit and leaves the room
答案 0 :(得分:1)
吸尘器(即你称之为" Agent",但为什么这样命名,因为它实际上是真空吸尘器?)只需要引用House对象它属于:
// a single House is constructed
House house = new House();
// omitted: add rooms to the house...
// create a first vacuum cleaner for the house. A reference to the house is given to this cleaner
VacuumCleaner vacuumCleaner = new VacuumCleaner(house);
System.out(vacuumCleaner.isRoomClean(2)); // prints false, because room 2 is full of dirt
vacuumCleaner.cleanRoom(2);
System.out(vacuumCleaner.isRoomClean(2)); // prints true, because the vacuum cleaner removed the dirt from room 2
// now let's create a second vacuum cleaner for the same house
VacuumCleaner vacuumCleaner2 = new VacuumCleaner(house);
System.out(vacuumCleaner2.isRoomClean(2)); // prints true, because room 2 has no dirt: it has previously been removed from the room by the first vacuum cleaner.
修改
以下是VacuumCleaner类的样子:
public class VacuumCleaner
/**
* The house that this vacuum cleaner cleans
*/
private House house;
public VacuumCleaner(House houseToClean) {
this.house = houseToClean;
}
public boolean isRoomDirty(int roomId) {
// find the room in the house, and see if it contains dirt
}
public void cleanRoom(int roomId) {
// find the room in the house, and remove dirt from it
}
}