您当前的位置: 首页 > 

杨林伟

暂无认证

  • 3浏览

    0关注

    3337博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

设计模式21 - 中介者模式【【Mediator Pattern】

杨林伟 发布时间:2018-03-15 19:51:34 ,浏览量:3

中介者模式

定义:

用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立的改变它们之间的交互。

举例(采购-销售-库房例子): 问题所在:如果销售一批产品,那么库房要改变,采购可能也要改变,这是每个类都会与其它类有依赖,耦合十分严重,此时就引出了中介者模式。下面看下类图:

这里写图片描述

public abstract class AbstractMediator { 
    protected Purchase purchase; 
    protected Sale sale; 
    protected Stock stock; 

    //构造函数
    public AbstractMediator(){ 
         purchase = new Purchase(this); 
         sale = new Sale(this); 
         stock = new Stock(this); 
    } 

    //中介者最重要的方法,叫做事件方法,处理多个对象之间的关系
    public abstract void execute(String str,Object...objects); 
}

------------------------------------------------------------------------

public class Mediator extends AbstractMediator { 

    //中介者最重要的方法
    public void execute(String str,Object...objects){ 
         if(str.equals("purchase.buy")){ //采购电脑
             this.buyComputer((Integer)objects[0]); 
         }else if(str.equals("sale.sell")){ //销售电脑
             this.sellComputer((Integer)objects[0]); 
         }else if(str.equals("sale.offsell")){ //折价销售
             this.offSell(); 
         }else if(str.equals("stock.clear")){ //清仓处理
             this.clearStock(); 
         } 
     } 

    //采购电脑
    private void buyComputer(int number){ 
         int saleStatus = super.sale.getSaleStatus(); 
         if(saleStatus>80){ //销售情况良好
             System.out.println("采购IBM电脑:"+number + "台"); 
             super.stock.increase(number); 
         }else{ //销售情况不好
             int buyNumber = number/2; //折半采购
             System.out.println("采购IBM电脑:"+buyNumber+ "台"); 
         } 
    } 

    //销售电脑
    private void sellComputer(int number){ 
         if(super.stock.getStockNumber()            
关注
打赏
1662376985
查看更多评论
0.3527s