中介者模式

本文介绍了中介者模式的定义及其在软件设计中的应用。该模式通过一个中介对象来封装一系列对象的交互行为,使得各个对象之间不需要直接引用彼此,降低耦合度。文中还提供了抽象中介者类的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

中介者模式的定义为: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.(用一个中介对象封装一系列的对象
交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它

们之间的交互。)


public abstract class Mediator {
//定义同事类
protected ConcreteColleague1 c1;
protected ConcreteColleague2 c2;
//通过getter/setter方法把同事类注入进来
public ConcreteColleague1 getC1() {
return c1;
}
public void setC1(ConcreteColleague1 c1) {
this.c1 = c1;
}
public ConcreteColleague2 getC2() {
return c2;
}
public void setC2(ConcreteColleague2 c2) {
this.c2 = c2;
}
//中介者模式的业务逻辑
public abstract void doSomething1();
public abstract void doSomething2();

}

中介者模式的优点就是减少类间的依赖,把原有的一对多的依赖变成了一对一的依赖,
同事类只依赖中介者,减少了依赖,当然同时也降低了类间的耦合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值