我读设计模式之MediatorPattern
using System;
///实现:多个对象之间的沟通,通过中介者来实现;
///避免了多对象之间直接关联造成的系统复杂性~
namespace MediatorPattern
{
class Program
{
static void Main(string[] args)
{
ConcreteMediator mediator = new ConcreteMediator();
MateA m1 = new MateA(mediator);
MateB m2 = new MateB(mediator);
mediator.mateA = m1;
mediator.mateB = m2;
m1.Send("are you ok?");
m2.Send("fine");
Console.Read();
}
}
public abstract class Mediator
{
public abstract void Send(string msg,ClassMate mate);
}
public class ConcreteMediator : Mediator
{
public MateA mateA { set; get; }
public MateB mateB { set; get; }
public override void Send(string msg, ClassMate mate)
{
if (mate == mateA)
{
mateB.Notify(msg);
}
else
{
mateA.Notify(msg);
}
}
}
public abstract class ClassMate
{
protected Mediator mediator;
public ClassMate(Mediator mediator)
{
this.mediator = mediator;
}
}
public class MateA : ClassMate
{
public MateA(Mediator mediator) : base(mediator) { }
public void Send(string msg)
{
mediator.Send(msg,this);
}
public void Notify(string msg)
{
Console.WriteLine("MateA 获得信息:"+msg);
}
}
public class MateB : ClassMate
{
public MateB(Mediator mediator) : base(mediator) { }
public void Send(string msg)
{
mediator.Send(msg, this);
}
public void Notify(string msg)
{
Console.WriteLine("MateB 获得信息:" + msg);
}
}
}
///实现:多个对象之间的沟通,通过中介者来实现;
///避免了多对象之间直接关联造成的系统复杂性~
namespace MediatorPattern
{
class Program
{
static void Main(string[] args)
{
ConcreteMediator mediator = new ConcreteMediator();
MateA m1 = new MateA(mediator);
MateB m2 = new MateB(mediator);
mediator.mateA = m1;
mediator.mateB = m2;
m1.Send("are you ok?");
m2.Send("fine");
Console.Read();
}
}
public abstract class Mediator
{
public abstract void Send(string msg,ClassMate mate);
}
public class ConcreteMediator : Mediator
{
public MateA mateA { set; get; }
public MateB mateB { set; get; }
public override void Send(string msg, ClassMate mate)
{
if (mate == mateA)
{
mateB.Notify(msg);
}
else
{
mateA.Notify(msg);
}
}
}
public abstract class ClassMate
{
protected Mediator mediator;
public ClassMate(Mediator mediator)
{
this.mediator = mediator;
}
}
public class MateA : ClassMate
{
public MateA(Mediator mediator) : base(mediator) { }
public void Send(string msg)
{
mediator.Send(msg,this);
}
public void Notify(string msg)
{
Console.WriteLine("MateA 获得信息:"+msg);
}
}
public class MateB : ClassMate
{
public MateB(Mediator mediator) : base(mediator) { }
public void Send(string msg)
{
mediator.Send(msg, this);
}
public void Notify(string msg)
{
Console.WriteLine("MateB 获得信息:" + msg);
}
}
}