中介者模式

时间:2020-06-30 19:04:07   收藏:0   阅读:12

名称:

    中介者模式(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();
    }
}

 

参考资料

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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!