中介者模式

Posted diameter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了中介者模式相关的知识,希望对你有一定的参考价值。

名称:

    中介者模式(Mediator Pattern)

 

问题:

    The Mediator pattern simplifies communication among objects in a system by introducing a single object that manages message distribution among other objects. The Mediator pattern promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.    

 

解决方案:

    

1、 模式的参与者

    1、Mediator

    -中介者定义一个接口用于与各同事对象通信。

    2、ConcerteMediator

   -具体中介者通过协调各同事对象实现写协作行为。

    -了解并维护它的各个同事。

    3、Colleague class

    -每一个同事类都知道它的中介者对象。

    -每一个同事对象在需与其他的同事通信的时候,与它的中介者通信。

 

2.实现方式

abstract class Mediator
{
    public abstract void register(Colleague colleague);
    public abstract void relay(Colleague cl); 
}
class ConcreteMediator extends Mediator
{
    private List<Colleague> colleagues=new ArrayList<Colleague>();
    public void register(Colleague colleague)
    {
        if(!colleagues.contains(colleague))
        {
            colleagues.add(colleague);
            colleague.setMedium(this);
        }
    }
    public void relay(Colleague cl)
    {
        for(Colleague ob:colleagues)
        {
            if(!ob.equals(cl))
            {
                ((Colleague)ob).receive();
            }   
        }
    }
}
abstract class Colleague
{
    protected Mediator mediator;
    public void setMedium(Mediator mediator)
    {
        this.mediator=mediator;
    }   
    public abstract void receive();   
    public abstract void send();
}
class ConcreteColleague1 extends Colleague
{
    public void receive()
    {
        System.out.println("Colleague1 receive。");
    }   
    public void send()
    {
        System.out.println("Colleague1 send。");
        mediator.relay(this); 
    }
}
class ConcreteColleague2 extends Colleague
{
    public void receive()
    {
        System.out.println("Colleague2 receive。");
    }   
    public void send()
    {
        System.out.println("Colleague2 send。");
        mediator.relay(this); 
    }
public class MediatorPattern
{
    public static void main(String[] args)
    {
        Mediator md=new ConcreteMediator();
        Colleague c1,c2;
        c1=new ConcreteColleague1();
        c2=new ConcreteColleague2();
        md.register(c1);
        md.register(c2);
        c1.send();
        System.out.println("-------------");
        c2.send();
    }
}

 

参考资料

《设计模式:可复用面向对象软件的基础》

以上是关于中介者模式的主要内容,如果未能解决你的问题,请参考以下文章

(十九)中介者模式-代码实现

设计模式之中介者模式

20160227.CCPP体系详解(0037天)

设计模式----中介者模式及简单总结(2018/10/30)

中介者模式分析结构图及基本代码

设计模式之中介者模式