Design Patterns - behavioral patterns of the intermediary model (seven)

Intermediary model

Intermediary model (Mediator Pattern) is used to reduce the complexity of communications between a plurality of objects and classes. This mode provides an intermediate class, which generally handles the communication between the different classes and the loosely coupled, making the code easier to maintain. Mediator pattern belongs behavioral patterns.

Introduction

Intent: with a mediation object that encapsulates a set of objects interact intermediary keeping objects explicitly referring to each other, so that it loosely coupled, and can be changed independently of the interaction between them.

Mainly to solve: there are a lot of objects and relationships between objects, this will inevitably lead to the structure of the system becomes very complicated, but if an object is changed, we also need to track objects associated with it, and make the appropriate treatment .

When to use: a plurality of classes coupled to each other to form a network structure.

How to solve: separating said network structure of the star structure.

The key code: the communication between the encapsulated object class Colleague a single process.

Application examples:  1, prior to China's accession to WTO countries trade with each other is a complex structure, it is by WTO countries to trade with each other. 2, airport scheduling system. 3, MVC frame, where C (controller) is M (models) and V (view) of the intermediary.

Advantages:  1, reduces the complexity of the class, converted into the one-to-many. 2, the decoupling between classes. 3, in line with the principles of Demeter.

Cons: Mediator will be huge, complicated by difficult to maintain.

Be used:  1, a reference to the presence of more complex relationships, dependencies between them leading to confusion and difficult to reuse the structure of the object between the objects in the system. 2, through a like plurality of intermediate class to encapsulate the behavior classes, and do not want to generate too many subclasses.

Note: should not be used when duty chaos.

achieve

Let's walk through the intermediary model chat rooms instance. Example, a plurality of users can send messages to the chat room, the chat room message is displayed to all users. We will create two classes  ChatRoom  and  the User . User  objects using  ChatRoom  ways to share their news.

MediatorPatternDemo , our demo class uses  User  objects to display the communication between them.

Mediator pattern UML diagram

step 1

Create the mediation classes.

ChatRoom.java

import java.util.Date;

public class ChatRoom {
   public static void showMessage(User user, String message){
      System.out.println(new Date().toString()
         + " [" + user.getName() +"] : " + message);
   }
}

Step 2

Create a user class.

User.java

public class User {
   private String name;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public User(String name){
      this.name  = name;
   }

   public void sendMessage(String message){
      ChatRoom.showMessage(this,message);
   }
}

Step 3

Use  User  object to display the communication between them.

MediatorPatternDemo.java

public class MediatorPatternDemo {
   public static void main(String[] args) {
      User robert = new User("Robert");
      User john = new User("John");

      robert.sendMessage("Hi! John!");
      john.sendMessage("Hello! Robert!");
   }
}

Step 4

The implementation of the program, output:

Thu Jan 31 16 : 05 : 46 IST 2013 [ Robert ] : Hi ! John ! Thu Jan 31 16 : 05 : 46 IST 2013 [ John ] : Hello ! Robert !               




In real life, there are many intermediary model's figure, such as QQ game platform, chat rooms, QQ group, messaging platforms, and real estate agent. Whether QQ game or QQ group, they are acting as a middle platform, QQ users can log in the middle of the platform to communicate with other QQ users, without these intermediate platform, if we want to chat with friends, it may need to face it it. Telephone, text messaging is also an intermediate platform, with this intermediate platform, users are not directly dependent on each other and users only need to rely on the middle platform on it, all the operations by the middle platform to distribute.

Intermediary model, defines a mediation object to encapsulate the interaction between a series of objects. Mediator the respective objects do not explicitly referring to each other between, so that the coupling is lowered, and can be changed independently interactions therebetween.

Design ideas and code implementation:

以现实生活中打牌的例子来实现下中介者模式。打牌总有输赢,对应的则是货币的变化,如果不用中介者模式的话,实现如下:

/// <summary>
/// 抽象牌友类
/// </summary> public abstract class AbstractCardPartner { public int Money { get; set; } public abstract void ChangeMoney(int money, AbstractCardPartner other); } /// <summary> /// 牌友A /// </summary> public class PartnerA : AbstractCardPartner { public override void ChangeMoney(int money, AbstractCardPartner other) { Money += money; other.Money -= money; } } /// <summary> /// 牌友B /// </summary> public class PartnerB : AbstractCardPartner { public override void ChangeMoney(int money, AbstractCardPartner other) { Money += money; other.Money -= money; } } /// <summary> /// 调用 /// </summary> /// <param name="args"></param> static void Main(string[] args) { AbstractCardPartner A = new PartnerA(); A.Money = 20; AbstractCardPartner B = new PartnerB(); B.Money = 20; // A赢了B的钱减少 A.ChangeMoney(5, B); Console.WriteLine("A 现在的钱是:{0}", A.Money); // 应该是25 Console.WriteLine("B 现在的钱是:{0}", B.Money); // 应该是15 // B赢了A的钱减少 B.ChangeMoney(10, A); Console.WriteLine("A 现在的钱是:{0}", A.Money); // 应该是15 Console.WriteLine("B 现在的钱是:{0}", B.Money); // 应该是25 Console.ReadLine(); }

这样的实现确实解决了上面场景中的问题,并且使用了抽象类使具体牌友A和牌友B都依赖于抽象类,从而降低了同事类之间的耦合度。但是如果其中牌友A发生变化时,此时就会影响到牌友B的状态,如果涉及的对象变多的话,这时候某一个牌友的变化将会影响到其他所有相关联的牌友状态。例如牌友A算错了钱,这时候牌友A和牌友B的钱数都不正确了,如果是多个人打牌的话,影响的对象就会更多。这时候就会思考——能不能把算钱的任务交给程序或者算数好的人去计算呢,这时候就有了我们QQ游戏中的欢乐斗地主等牌类游戏了。

进一步完善的方案,即加入一个中介者对象来协调各个对象之间的关联,这也就是中介者模式的应用了,具体完善后的实现代码如下所示:

/// <summary>
/// 抽象牌友类
/// </summary> public abstract class AbstractCardPartner { public int Money { get; set; } public abstract void ChangeMoney(int money, AbstractMediator mediator); } /// <summary> /// 牌友A /// </summary> public class PartnerA : AbstractCardPartner { public override void ChangeMoney(int money, AbstractMediator mediator) { mediator.AWin(money); } } /// <summary> /// 牌友B /// </summary> public class PartnerB : AbstractCardPartner { public override void ChangeMoney(int money, AbstractMediator mediator) { mediator.BWin(money); } } /// <summary> /// 抽象中介者类 /// </summary> public abstract class AbstractMediator { protected AbstractCardPartner A; protected AbstractCardPartner B; public AbstractMediator(AbstractCardPartner a, AbstractCardPartner b) { A = a; B = b; } public abstract void AWin(int money); public abstract void BWin(int money); } /// <summary> /// 调用 /// </summary> /// <param name="args"></param> static void Main(string[] args) { AbstractCardPartner A = new PartnerA(); AbstractCardPartner B = new PartnerB(); A.Money = 20; B.Money = 20; AbstractMediator mediator = new MediatorPater(A, B); // A赢了 A.ChangeMoney(5, mediator); Console.WriteLine("A 现在的钱是:{0}", A.Money); // 应该是25 Console.WriteLine("B 现在的钱是:{0}", B.Money); // 应该是15 // B赢了 B.ChangeMoney(10, mediator); Console.WriteLine("A 现在的钱是:{0}", A.Money); // 应该是15 Console.WriteLine("B 现在的钱是:{0}", B.Money); // 应该是25 Console.ReadLine(); }

在上面的实现代码中,抽象中介者类保存了两个抽象牌友类,如果新添加一个牌友类似时,此时就不得不去更改这个抽象中介者类。可以结合观察者模式来解决这个问题,即抽象中介者对象保存抽象牌友的类别,然后添加Register和UnRegister方法来对该列表进行管理,然后在具体中介者类中修改AWin和BWin方法,遍历列表,改变自己和其他牌友的钱数。这样的设计还是存在一个问题——即增加一个新牌友时,此时虽然解决了抽象中介者类不需要修改的问题,但此时还是不得不去修改具体中介者类,即添加CWin方法,我们可以采用状态模式来解决这个问题,关于状态模式的介绍将会在下一篇进行介绍。

中介者模式的优缺点

优点:

  • 简化了对象之间的关系,将系统的各个对象之间的相互关系进行封装,将各个同事类解耦,使得系统变为松耦合。
  • 提供系统的灵活性,使得各个同事对象独立而易于复用。

缺点:

  • 中介者模式中,中介者角色承担了较多的责任,所以一旦这个中介者对象出现了问题,整个系统将会受到重大的影响。
  • 新增加一个同事类时,不得不去修改抽象中介者类和具体中介者类,此时可以使用观察者模式和状态模式来解决这个问题。

中介者模式的适用场景

以下情况下可以考虑使用中介者模式:

  • 一组定义良好的对象,现在要进行复杂的相互通信。
  • I want an intermediate class to encapsulate the plurality of classes of behavior, but do not want to generate too many subclasses.

Guess you like

Origin www.cnblogs.com/yuexiaoyun/p/11886430.html