中介者设计模式(公司部门打交道示例)
0. UML结构图
1. 公司部门 Code
1.1 部门接口
public interface Department {
void selfAction ( ) ;
void outAction ( ) ;
}
1.2 部门基类
public abstract class BaseDepartment implements Department {
protected Mediator mediator;
public BaseDepartment ( Mediator mediator) {
this . mediator = mediator;
}
@Override
public abstract void selfAction ( ) ;
@Override
public abstract void outAction ( ) ;
}
1.3 研发部
public class Development extends BaseDepartment {
public Development ( Mediator mediator) {
super ( mediator) ;
}
@Override
public void selfAction ( ) {
System. out. println ( "Development.selfAction 研发产品" ) ;
}
@Override
public void outAction ( ) {
System. out. println ( "Development.outAction 没钱了,需要支援" ) ;
mediator. command ( "financial" ) ;
}
}
1.4 市场部
public class Market extends BaseDepartment {
public Market ( Mediator mediator) {
super ( mediator) ;
}
@Override
public void selfAction ( ) {
System. out. println ( "Market.selfAction 拓展市场项目" ) ;
}
@Override
public void outAction ( ) {
System. out. println ( "Market.outAction 没钱了,需要支援" ) ;
mediator. command ( "financial" ) ;
}
}
1.5 财务部
public class Financial extends BaseDepartment {
public Financial ( Mediator mediator) {
super ( mediator) ;
}
@Override
public void selfAction ( ) {
System. out. println ( "Financial.selfAction 统计财务情况,发钱" ) ;
}
@Override
public void outAction ( ) {
System. out. println ( "Financial.outAction" ) ;
}
}
2. 公司总经理(中介)Code
2.1 中介接口
public interface Mediator {
void register ( String name, Department department) ;
void command ( String name) ;
}
2.2 总经理
public class President implements Mediator {
private Map< String, Department> map = new HashMap < > ( ) ;
@Override
public void register ( String name, Department department) {
map. put ( name, department) ;
}
@Override
public void command ( String name) {
map. get ( name) . selfAction ( ) ;
}
}
3. 公司部门打交道示例 Test
public class MediatorTest {
public static void main ( String[ ] args) {
President president = new President ( ) ;
Department development = new Development ( president) ;
Department market = new Market ( president) ;
Department financial = new Financial ( president) ;
president. register ( "development" , development) ;
president. register ( "market" , market) ;
president. register ( "financial" , financial) ;
development. selfAction ( ) ;
development. outAction ( ) ;
market. selfAction ( ) ;
market. outAction ( ) ;
}
}