C# 设计模式-中介者(Mediator)

用一个中介对象来封装一系列对象的交互,使得各对象不需要显示地相互引用,从而耦合松散。


主要组成:

Mediator-中介者父类或接口

ConcreteMediator-具体中介者

Colleague-同事父类

ConcreteColleague-具体同事类


相关类:

using System;
using System.Collections.Generic;

namespace Mediator
{
    /// 
    /// 中介者父类或接口
    /// 
    abstract class Mediator
    {
        public abstract void Connect(int dialNumber);
    }

    /// 
    /// 基站(具体中介者)
    /// 
    class BaseStationMediator : Mediator
    {
        Dictionary numberAndPhones = new Dictionary();

        public void AddPhone(PhoneClass phone)
        {
            if (numberAndPhones.ContainsKey(phone.MyPhoneNumber))
            {
                return;
            }
            numberAndPhones.Add(phone.MyPhoneNumber, phone);
        }
        //基站转接号码
        public override void Connect(int dialNumber)
        {
            if (numberAndPhones.ContainsKey(dialNumber))
            {
                Console.WriteLine("接通号码:{0}", dialNumber);
            }
            else
            {
                Console.WriteLine("对不起,您拨打的号码是空号!");
            }
        }
    }

    /// 
    /// 电话父类
    /// 
    abstract class PhoneClass
    {
        //基站
        public Mediator BaseStation;

        /// 
        /// 本机号码
        /// 
        public int MyPhoneNumber { get; set; }

        public PhoneClass(int myPhoneNumber, Mediator baseStation)
        {
            MyPhoneNumber = myPhoneNumber;
            BaseStation = baseStation;
        }
        //拨打电话
        public abstract void Dial(int dialNumber);
    }

    /// 
    /// 手机
    /// 
    class Cellphone : PhoneClass
    {
        public Cellphone(int myPhoneNumber, Mediator baseStation)
            : base(myPhoneNumber, baseStation)
        {
        }

        public override void Dial(int dialNumber)
        {
            BaseStation.Connect(dialNumber);
        }
    }

    /// 
    /// 座机
    /// 
    class Telephone : PhoneClass
    {
        public Telephone(int myPhoneNumber, Mediator baseStation)
            : base(myPhoneNumber, baseStation)
        {
        }

        public override void Dial(int dialNumber)
        {
            BaseStation.Connect(dialNumber);
        }

    }
}

调用:

using System;

namespace Mediator
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseStationMediator baseStation = new BaseStationMediator();
            Cellphone cellphone = new Cellphone(138, baseStation);
            Telephone telephone = new Telephone(555, baseStation);
            //添加电话到基站
            baseStation.AddPhone(cellphone);
            baseStation.AddPhone(telephone);
            //拨打号码
            cellphone.Dial(555);
            cellphone.Dial(222);

            Console.Read();
        }
    }
}

结果:

C# 设计模式-中介者(Mediator)_第1张图片

参考资料:《设计模式-可复用面对对象软件的基础》


你可能感兴趣的:(C#-设计模式)