Mediator中介者(行为模式)

mac2022-06-30  19

动机(Motivation)在软件构建过程中,经常会现多个对象互相关联交互的情况,对象之间经常会维

持一种复杂的引用关系,如果遇到 一些需求的更改,这种直接的引用关系将面临不断的变化。在这种情况下,我们可以使用一个中介对象来管理对象间的关联关系,避免相互

交互对之间的紧耦合引用关系,从面更好的解耦。意图(Intent)用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式的相互引

用,从而使期耦合松散,而且可以独立地改变它们之间的交互。代码(Code)class MenuItem{  TextArea textArea;  ClipBorad clipBorad;  ToolBarButton toolBarButton;

  public void Click()  {    string text = textArea.SelectedText();     textArea.RemoveSelectText();     clipBoard.SetData(text);     toolBarButton.EnabledPasteButton(true);  }}}

class TextArea{  MenuItem cutMenuItem;  ClipBorad clipBorad;  ToolBarButton toolBarButton;}

class ClipBorad{}

class ToolBarButton{}改进abstract class Mediator{    public abstract void Notify();}

class CutMenuItem{   Mediator mediator;   public void Click()   {      mediator.Notify();   }}Mediator模式的要点1.将多个对象间复杂的关联关系解耦,Mediator模式将多个对象间的控制逻辑进

行集中管理,变多个对象互相关联为多个对象和一个中介者关联,简化了系统的

维护,抵御了可能的变化。2.随着控制逻辑的复杂化,Mediator模式具体对象的实现可能 相当复杂。这时候

可以对Mediator对象进行分解处理。3.Facade模式是解耦系统外到系统内(单向)的对象关联关系;Mediator模式解

耦系统内部各个对象之间(双向的)的关联关系。

转载于:https://www.cnblogs.com/hotsoho.net/articles/520740.html

最新回复(0)