设计模式(17)-行为型-中介者模式(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"));
        mediator.notice("buyer");
        mediator.notice("seller");
    }

}

结果

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


<script type="text/javascript"><!-- google_ad_client = "ca-pub-7104628658411459"; /* wide1 */ google_ad_slot = "8564482570"; google_ad_width = 728; google_ad_height = 90; //--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值