Net设计模式实例之中介者模式(Mediator Pattern)

简介: 一、中介者模式简介(Brief Introduction) 中介者模式(Mediator Pattern),定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互。

一、中介者模式简介(Brief Introduction

中介者模式(Mediator Pattern),定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互。 Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently

中介者减少了各个同事对象的耦合,使得可以独立地改变和复用各个同事对象和中介者类;由于把对想如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到他们之间的交互上来,也就是站在一个更宏伟的角度去考虑系统。

二、解决的问题(What To Solve

中介者模式一般应用于一组对象以定义良好但是复杂的方法进行通信的场合,以及想定制一个分布在多个类中的行为,而不想生成太多的子类的场合。

三、中介者模式分析(Analysis

1、中介者模式结构

Mediator:抽象中介者,定义了同事对象交互的接口。

ConcreteMediator:具体中介者对象,实现抽象类中的方法,此具体中介者对象需要知道所有具体同事类,并从具体同事接受消息,向具体同事对象发送命令。

Colleague类:抽象同事类。

ConcreteColleague1类,ConcreteColleague2:具体同事类,实现抽象同事类中的方法。每一个同时类需要知道中介者对象;每个具体同事类只需要了解自己的行为,而不需要了解其他同事类的情况。

2、源代码

1中介者类Mediator及其具体实现类ConcreteMediator

/// <summary>

/// The 'Mediator' abstract class

/// </summary>

abstract class Mediator

{

    public abstract void Send(string message,Colleague colleague);

}

/// <summary>

/// The 'ConcreteMediator' class

/// </summary>

class ConcreteMediator : Mediator

{

    private ConcreteColleague1 _colleague1;

    private ConcreteColleague2 _colleague2;

    public ConcreteColleague1 Colleague1

    {

        set { _colleague1 = value; }

    }

 

    public ConcreteColleague2 Colleague2

    {

        set { _colleague2 = value; }

    }

    public override void Send(string message,Colleague colleague)

    {

        if (colleague == _colleague1)

        {

            _colleague2.Notify(message);

        }

        else

        {

            _colleague1.Notify(message);

        }

    }

}

 

2、抽象同事类Colleague及其实现类ConcreteColleague1ConcreteColleague2

/// <summary>

/// The 'Colleague' abstract class

/// </summary>

abstract class Colleague

{

    protected Mediator mediator;

    // Constructor

    public Colleague(Mediator mediator)

    {

        this.mediator = mediator;

    }

}

/// <summary>

/// A 'ConcreteColleague' class

/// </summary>

class ConcreteColleague1 : Colleague

{

 

    // Constructor

    public ConcreteColleague1(Mediator mediator)

 

        : base(mediator)

    {

    }

    public void Send(string message)

    {

        mediator.Send(message, this);

    }

    public void Notify(string message)

    {

        Console.WriteLine("Colleague1 gets message: "+ message);

    }

}

/// <summary>

/// A 'ConcreteColleague' class

/// </summary>

class ConcreteColleague2 : Colleague

{

    // Constructor

    public ConcreteColleague2(Mediator mediator)

 

        : base(mediator)

    {

    }

    public void Send(string message)

    {

        mediator.Send(message, this);

    }

    public void Notify(string message)

    {

        Console.WriteLine("Colleague2 gets message: "+ message);

    }

}

 

3、客户端代码

static void Main(string[] args)

{

    ConcreteMediator m = new ConcreteMediator();

    ConcreteColleague1 c1 = new ConcreteColleague1(m);

    ConcreteColleague2 c2 = new ConcreteColleague2(m);

    m.Colleague1 = c1;

    m.Colleague2 = c2;

    c1.Send("How are you? JamesHao");

    c2.Send("Fine, thanks");

    // Wait for user

    Console.ReadKey();

}

3、程序运行结果

四.中介者模式案例分析(Example

1、场景

实现一个聊天室功能,聊城室就是一个中介者,参与聊天的人就是同事对象,如下图所示

AbstractChatroom:抽象聊天室类,做为Participant的交互的中介。

Register()方法:会员注册功能;Send()方法:发送消息功能。

Chatroom:具体聊天室类,实现抽象聊天室类中的方法。

Participant:参与者类,主要有发送消息Send()功能和接受消息Receive()功能。

Beatle类,NonBeatle:参与者类的具体实现,实现父类Paticipant类中的方法。

2、代码

1、抽象聊天室类AbstractChatroom及其具体聊天室Chatroom

/// <summary>

/// The 'Mediator' abstract class

/// </summary>

abstract class AbstractChatroom

{

    public abstract void Register(Participant participant);

    public abstract void Send(string from, string to, string message);

}

/// <summary>

/// The 'ConcreteMediator' class

/// </summary>

class Chatroom : AbstractChatroom

{

    private Dictionary<string, Participant> _participants =new Dictionary<string, Participant>();

    public override void Register(Participant participant)

    {

        if (!_participants.ContainsValue(participant))

        {

            _participants[participant.Name] = participant;

        }

        participant.Chatroom = this;

 

    }

    public override void Send(string from, string to, string message)

    {

        Participant participant = _participants[to];

        if (participant != null)

        {

            participant.Receive(from, message);

        }

    }

}

 

2、参与者Participant类及其实现BeatleNonBeatle

/// <summary>

/// The 'AbstractColleague' class

/// </summary>

class Participant

{

    private Chatroom _chatroom;

    private string _name;

    // Constructor

    public Participant(string name)

    {

        this._name = name;

    }

    // Gets participant name

    public string Name

    {

        get { return _name; }

    }

    // Gets chatroom

    public Chatroom Chatroom

    {

        set { _chatroom = value; }

        get { return _chatroom; }

    }

    // Sends message to given participant

    public void Send(string to, string message)

    {

        _chatroom.Send(_name, to, message);

    }

    // Receives message from given participant

    public virtual void Receive(string from, string message)

    {

        Console.WriteLine("{0} to {1}: '{2}'",from, Name, message);

    }

}

/// <summary>

/// A 'ConcreteColleague' class

/// </summary>

class Beatle : Participant

{

    // Constructor

    public Beatle(string name)

        : base(name)

    {

    }

    public override void Receive(string from, string message)

    {

        Console.Write("To a Beatle: ");

        base.Receive(from, message);

    }

}

/// <summary>

/// A 'ConcreteColleague' class

/// </summary>

class NonBeatle : Participant

{

    // Constructor

    public NonBeatle(string name)

        : base(name)

    {

    }

    public override void Receive(string from, string message)

    {

        Console.Write("To a non-Beatle: ");

        base.Receive(from, message);

    }

}

 

3、客户端代码

static void Main(string[] args)

{

    // Create chatroom

    Chatroom chatroom = new Chatroom();

    // Create participants and register them

    Participant George = new Beatle("George");

    Participant Paul = new Beatle("Paul");

    Participant Ringo = new Beatle("Ringo");

    Participant John = new Beatle("John");

    Participant Yoko = new NonBeatle("Yoko");

 

    chatroom.Register(George);

    chatroom.Register(Paul);

    chatroom.Register(Ringo);

    chatroom.Register(John);

    chatroom.Register(Yoko);

   

    // Chatting participants

    Yoko.Send("John", "Hi John!");

    Paul.Send("Ringo", "All you need is love");

    Ringo.Send("George", "My sweet Lord");

    Paul.Send("John", "Can't buy me love");

    John.Send("Yoko", "My sweet love");

    // Wait for user

    Console.ReadKey();

}

3、运行结果

五、总结(Summary

中介者模式(Mediator Pattern),定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互。中介者模式一般应用于一组对象以定义良好但是复杂的方法进行通信的场合,以及想定制一个分布在多个类中的行为,而不想生成太多的子类的场合。

参考:http://www.dofactory.com/Patterns/PatternMediator.aspx

 

版权

作者:灵动生活 郝宪玮

出处:http://www.cnblogs.com/ywqu

如果你认为此文章有用,请点击底端的【推荐】让其他人也了解此文章,

img_2c313bac282354945ea179a807d7e70d.jpg

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

相关文章
|
C# 设计模式 .NET
使用C# (.NET Core) 实现状态设计模式 (State Pattern)
本文的概念性内容来自深入浅出设计模式一书 项目需求 这是一个糖果机的需求图.  它有四种状态, 分别是图中的四个圆圈: No Quarter: 无硬币 Has Quater 有硬币 Gumball Sold 糖果卖出 Out of Gumball 没有糖果了 这个图很像一个状态图.
1781 0
|
C#
使用C# (.NET Core) 实现组合设计模式 (Composite Pattern)
本文的概念性内容来自深入浅出设计模式一书. 本文需结合上一篇文章(使用C# (.NET Core) 实现迭代器设计模式)一起看. 上一篇文章我们研究了多个菜单一起使用的问题. 需求变更 就当我们感觉我们的设计已经足够好的时候, 新的需求来了, 我们不仅要支持多种菜单, 还要支持菜单下可以拥有子菜单.
1401 0
|
Java C# 设计模式
使用C# (.NET Core) 实现迭代器设计模式 (Iterator Pattern)
本文的概念来自深入浅出设计模式一书 项目需求 有两个饭店合并了, 它们各自有自己的菜单. 饭店合并之后要保留这两份菜单. 这两个菜单是这样的: 菜单项MenuItem的代码是这样的: 最初我们是这样设计的, 这是第一份菜单: 这是第2份菜单: 同时有两个菜单存在的问题 问题就是多个菜单把事情变复杂了.
1003 0
|
算法 C# Java
使用C# (.NET Core) 实现模板方法模式 (Template Method Pattern)
本文的概念内容来自深入浅出设计模式一书. 项目需求 有一家咖啡店, 供应咖啡和茶, 它们的工序如下: 咖啡: 茶: 可以看到咖啡和茶的制作工序是差不多的, 都是有4步, 其中有两步它们两个是一样的, 另外两步虽然具体内容不一样, 但是都做做的同一类工作.
1309 0
|
Java C#
使用C# (.NET Core) 实现适配器模式 (Adapter Pattern) 和外观模式 (Facade Pattern)
本文的概念内容来自深入浅出设计模式一书 现实世界中的适配器(模式) 我带着一个国标插头的笔记本电脑, 来到欧洲, 想插入到欧洲标准的墙壁插座里面, 就需要用中间这个电源适配器. 面向对象的适配器 你有个老系统, 现在来了个新供应商的类, 但是它们的接口不同, 如何使用这个新供应商的类呢? 首先, 我们不想修改现有代码, 你也不能修改供应商的代码.
1722 0
|
C#
使用C# (.NET Core) 实现命令设计模式 (Command Pattern)
本文的概念内容来自深入浅出设计模式一书. 项目需求 有这样一个可编程的新型遥控器, 它有7个可编程插槽, 每个插槽可连接不同的家用电器设备. 每个插槽对应两个按钮: 开, 关(ON, OFF).
820 0
|
Java C#
使用C# (.NET Core) 实现单体设计模式 (Singleton Pattern)
本文的概念内容来自深入浅出设计模式一书 由于我在给公司做内培, 所以最近天天写设计模式的文章.... 单体模式 Singleton 单体模式的目标就是只创建一个实例. 实际中有很多种对象我们可能只需要它们的一个实例, 例如: 线程池,缓存, 弹出的对话框, 用于保存设置的类, 用于logging的类, 硬件设备驱动对象等等.
1178 0
|
C#
使用C# (.NET Core) 实现抽象工厂设计模式 (Abstract Pattern)
本文的概念性内容来自深入浅出设计模式一书. 上一篇文章讲了简单工厂和工厂方法设计模式 http://www.cnblogs.com/cgzl/p/8760250.html, 使用的是披萨店的例子. 文将继续使用这个例子, 这里要用到抽象工厂.
1334 0
|
C# 设计模式 .NET
使用C# (.NET Core) 实现简单工厂(Simple Factory) 和工厂方法设计模式 (Factory Method Pattern)
本文源自深入浅出设计模式. 只不过我是使用C#/.NET Core实现的例子.   前言 当你看见new这个关键字的时候, 就应该想到它是具体的实现. 这就是一个具体的类, 为了更灵活, 我们应该使用的是接口(interface).
1401 0
|
安全 C# 数据安全/隐私保护
使用C# (.NET Core) 实现装饰模式 (Decorator Pattern) 并介绍 .NET/Core的Stream
该文章综合了几本书的内容. 某咖啡店项目的解决方案 某咖啡店供应咖啡, 客户买咖啡的时候可以添加若干调味料, 最后要求算出总价钱. Beverage是所有咖啡饮料的抽象类, 里面的cost方法是抽象的.
1344 0