Sometimes you may need to register objects connected to a port. This can be used to establish direct communication between agents: if object has a list of references to connected objects, it can directly interact with them by calling their functions, modifying parameters, etc. The list of connected objects can also be used as a list of addresses in message routing, when you need to send messages only to some certain objects rather than to all of them.
Agent registration can be implemented in different ways. The following is the simplest: at the model startup each agent sends a registration message with a reference to itself, via all connections. At destination ports, these references are extracted from messages and added to lists of connected objects.
registration of connected objects
Let's examine the just typed code. First goes the class constructor, that actually invokes the standard constructor of the base class Port.
The method receive() is called on message arrival. Here we check the type of arrived message. In the case it’s a registration message, the message sender is added to the list of connected objects (our connectedObjects collection). Otherwise, the message is processed according to the logic of your model.
The method register() sends a registration message, carrying the reference to the agent accessed by the method getAgent() of the port.
Now we have finished implementing object registration mechanism. Connected objects can be accessed from connectedObjects collection using its API.However, one agent may have multiple ports. In this case you need to build a list of connected ports, not a list of connected objects, to distinguish messages sent from different ports of the same object. To implement it, make minor changes in the described mechanism: your custom port class should have field port of type MyPort, and the method register() should send not a reference to agent class, but a reference to a port itself, which can be obtained via the command this.