Mediator pattern is a behavioral pattern that coordinates and encapsulates many-to-many communication/interaction among related objects (Colleagues) so that Colleagues interact not directly with other independent Colleagues, but indirectly with other Colleagues through a centralized Mediator. source: GoF Each Colleague references the Mediator. In reverse, the Mediator references the registered Colleagues. Object Structure, source: GoF overviewMediator pattern involves two abstraction trees - Mediator inheritance hierarchy and Colleague inheritance hierarchy. All Colleagues should interact with the mediator object, instead of each other. Think of Mediator as a centralized traffic controller or a stock exchange where participating brokerages have their buy/sell orders fulfilled. To loosely couple participating objects (Colleagues), the Mediator object must encapsulates and keep references to all participating objects (Colleagues). One way of achieving this is to provide methods (e.g. Mediator.addXXXX(Colleague) or Mediator.registerXXXX(Colleague)) for registering Colleagues. The timing of registering a Colleague can be when a Colleague is constructed. Once registered with the Mediator, Colleagues are either consumer or producer. Each participating Colleague object encapsulates a Mediator through its constructor. When a Colleague is constructed, it register itself with the Mediator. When a Colleague object’s internal state changes through operation (e.g. calling sellOffer()), it delegates and reports that state change to the Mediator by calling Mediator.sellOffer() that goes through multiple participated Colleagues registered with the Mediator, acting something like a controller in Model/View/Controller architecture. mediator design pattern code exampleThe following source are taken from New Think Tank by Derek Banas. Please visit his blog and support his awesome work. public class StockOffer{ Colleague: Register Colleague with Mediator.public abstract class Colleague{ [1] Register Colleague with Mediator. [2] Delegate change/operation to Mediator. Mediator: public interface Mediator { [1] Encapsulate with references to participating Colleague. [2] Inter-communication is encapsulated by Mediator. [3] The code called by Colleague's constructor that actually registers a colleague. when to use mediator design pattern
references
0 Comments
Leave a Reply. |
Categories
All
Archives
May 2020
|