码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式------中介者模式

时间:2019-10-22 18:05:42      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:ext   ted   col   使用   bst   set   参考   textbox   列表   

中介者模式:
定义一个对象来封装一系列对象的交互.

中介者的四个角色:
1.Mediator(抽象中介者)
2.ConcreteMediator(具体中介者)
3.Colleague(抽象同事类)
4.ConcreteColleague(具体同事类)

举例说明:
例如公司开发一套CRM系统,该系统负责编辑客户的信息,其中有一个UI界面负责显示和修改客户信息.
该界面包括列表框,组合框,文本框,在这三个框内编辑用户信息,其他框内的信息都要相应的改变.

具体实现:

 

/**
*
* @ClassName: Mediator
* @Description: 抽象中介者类
* @author haibiscuit
* @date 2019年10月22日 下午5:10:26
*
*/

 

public abstract class Mediator {
ArrayList<Mycomponent> arrayList;
protected void addMyComponent(Mycomponent c) {
if (null == arrayList) {
arrayList = new ArrayList<Mycomponent>();
}
arrayList.add(c);
};

public abstract void ComponentChanged(Mycomponent c);

 

}

 


/**
*
* @ClassName: ConcreteMediator
* @Description: 具体中介者类
* @author haibiscuit
* @date 2019年10月22日 下午5:11:41
*
*/
public class ConcreteMediator extends Mediator{
// 封装同事对象的交互
@Override
public void ComponentChanged(Mycomponent c) {
for (Mycomponent mycomponent : arrayList) {
mycomponent.Update();
}
}
}

 

/**
*
* @ClassName: Mycomponent
* @Description: 抽象组件类,充当抽象同事类
* @author haibiscuit
* @date 2019年10月22日 下午5:07:02
*
*/
public abstract class Mycomponent {
protected Mediator mediator;


public void setMediator(Mediator mediator) {
this.mediator = mediator;

}

//转发调用
public void changed() {
mediator.ComponentChanged(this);
}

public abstract void Update();
}

 

/**
*
* @ClassName: MyComboBox
* @Description: 组合框类,充当同事类
* @author haibiscuit
* @date 2019年10月22日 下午5:21:05
*
*/
public class MyComboBox extends Mycomponent{

@Override
public void Update() {
System.out.println("组合框修改信息");
}

}

 

/**
*
* @ClassName: MyList
* @Description: 列表框类,充当具体同事
* @author haibiscuit
* @date 2019年10月22日 下午5:19:11
*
*/
public class MyList extends Mycomponent{

@Override
public void Update() {
System.out.println("列表框修改信息");
}
}

 

/**
*
* @ClassName: MyTextBox
* @Description: 文本框类,充当同事类
* @author haibiscuit
* @date 2019年10月22日 下午5:19:45
*
*/
public class MyTextBox extends Mycomponent{

@Override
public void Update() {
System.out.println("文本框修改信息");
}
}

总结:

    中介者模式很像观察者模式,具体的使用场景和比较可以参考观察者模式.

 

设计模式------中介者模式

标签:ext   ted   col   使用   bst   set   参考   textbox   列表   

原文地址:https://www.cnblogs.com/haibiscuit/p/11721338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!