打字猴:1.700462623e+09
1700462623 设计模式之禅 [:1700453975]
1700462624 设计模式之禅 14.2 中介者模式的定义
1700462625
1700462626 中介者模式的定义为:Define an object that encapsulates how a set of objects interact.Mediator promotes loose coupling by keeping objects from referring to each other explicitly,and it lets you vary their interaction independently.(用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它们之间的交互。)
1700462627
1700462628 中介者模式通用类图如图14-7所示。
1700462629
1700462630
1700462631
1700462632
1700462633 图14-7 中介者模式通用类图
1700462634
1700462635 从类图中看,中介者模式由以下几部分组成:
1700462636
1700462637 ❑Mediator抽象中介者角色
1700462638
1700462639 抽象中介者角色定义统一的接口,用于各同事角色之间的通信。
1700462640
1700462641 ❑Concrete Mediator具体中介者角色
1700462642
1700462643 具体中介者角色通过协调各同事角色实现协作行为,因此它必须依赖于各个同事角色。
1700462644
1700462645 ❑Colleague同事角色
1700462646
1700462647 每一个同事角色都知道中介者角色,而且与其他的同事角色通信的时候,一定要通过中介者角色协作。每个同事类的行为分为两种:一种是同事本身的行为,比如改变对象本身的状态,处理自己的行为等,这种方法叫做自发行为(Self-Method),与其他的同事类或中介者没有任何的依赖;第二种是必须依赖中介者才能完成的行为,叫做依赖方法(Dep-Method)。
1700462648
1700462649 中介者模式比较简单,其通用源码也比较简单,先看抽象中介者Mediator类,如代码清单14-12所示。
1700462650
1700462651 代码清单14-12 通用抽象中介者
1700462652
1700462653 public abstract class Mediator{
1700462654
1700462655 //定义同事类
1700462656
1700462657 protected ConcreteColleague1 c1;
1700462658
1700462659 protected ConcreteColleague2 c2;
1700462660
1700462661 //通过getter/setter方法把同事类注入进来
1700462662
1700462663 public ConcreteColleague1 getC1(){
1700462664
1700462665 return c1;
1700462666
1700462667 }
1700462668
1700462669 public void setC1(ConcreteColleague1 c1){
1700462670
1700462671 this.c1=c1;
1700462672
[ 上一页 ]  [ :1.700462623e+09 ]  [ 下一页 ]