当前位置:编程学习 > JAVA >>

设计模式-行为型-中介者模式(Mediator)

概述
    用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
适用性
    1.一组对象以定义良好但是复杂的方式进行通信。产生的相互依赖关系结构混乱且难以理解。

    2.一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象。

    3.想定制一个分布在多个类中的行为,而又不想生成太多的子类。
   
参与者
    1.Mediator
      中介者定义一个接口用于与各同事(Colleague)对象通信。

    2.ConcreteMediator
      具体中介者通过协调各同事对象实现协作行为。
      了解并维护它的各个同事。

    3.Colleagueclass
      每一个同事类都知道它的中介者对象。
      每一个同事对象在需与其他的同事通信的时候,与它的中介者通信

类图

示例
package com.sql9.actioned; 
 
/**
 * 中介者模式 示例, 以二手房买卖为例 :)
 * @author sean
 */ 
 
abstract class Mediator { 
    public abstract void notice(String content); 

 
interface Customer { 
    void action(); 

 
// 买方 
class Buyer implements Customer { 
     
    String target; 
     
    public Buyer(String target) { 
        this.target = target; 
    } 
     
    @Override 
    public void action() { 
        System.out.println(target + " will buy the target house"); 
    } 
     

 
// 卖方 
class Seller implements Customer { 
    String source; 
    String address; 
    public Seller(String source, String address) { 
        this.source = source; 
        this.address = address; 
    } 
    @Override 
    public void action() { 
        System.out.println(source + " will sell the house: " + address); 
    } 
     

 
class ConcreteMediator extends Mediator { 
 
    private Customer custA; //买方 
    private Customer custB; //卖方 
     
    public ConcreteMediator(Customer custA, Customer custB) { 
        this.custA = custA; 
        this.custB = custB; 
    } 
     
    @Override 
    public void notice(String content) { 
        System.out.println("notice conent: " + content); 
        if ("buyer".equals(content)) { 
            custA.action(); 
        } 
        else if ("seller".equals(content)) { 
            custB.action(); 
        } 
        else { 
            System.out.println("invalid notice content"); 
        } 
    } 
     

 
public class MediatorTest { 
 
    public static void main(String[] args) { 
        Mediator mediator = new ConcreteMediator(new Buyer("张三"), new Seller("李四", "abc广场小区x号院yyy"));  www.zzzyk.com
        mediator.notice("buy er"); 
        mediator.notice("seller"); 
    } 
 

结果
notice conent: buyer 
张三 will buy the target house 
notice conent: seller 
李四 will sell the house: abc广场小区x号院yyy 

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,