中介者模式:
1、定义:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,
从而使其耦合松散,而且可以独立地改变它们之间的交互
2、模型结构:
(1)抽象中介者(Mediator):它是中介者的接口,提供了同事对象注册与转发同事对象信息的抽象方法
(2)具体中介者(ConcreteMediator):实现中介者接口,通过一个数据结构来管理同事对象,
协调各个同事角色之间的交互关系,因此它依赖于同事角色
(3)抽象同事类(Colleague):定义同事类的接口,保存中介者对象,提供同事对象交互的抽象方法,
实现所有相互影响的同事类的公共功能
(4)具体同事类(Concrete Colleague):抽象同事类的实现者,当与其他同事对象交互时,中介者对象负责后续的交互
3、优点:
(1)降低了对象之间的耦合性,使得对象易于独立地被复用
(2)将对象间的一对多关联转变为一对一的关联,提高系统的灵活性,使得系统易于维护和扩展
(3)减少子类生成
4、缺点:当同事类太多时,中介者的职责将很大,它会变得复杂而庞大,以至于系统难以维护
5、适用环境:
(1)当对象之间存在复杂的网状结构关系而导致依赖关系混乱且难以复用时
(2)当想创建一个运行于多个类之间的对象,又不想生成新的子类时
// 抽象中介者 abstract class Mediator { abstract register(colleague: Colleague): void; abstract relay(colleague: Colleague): void; } // 具体中介者 class ConcreteMediator extends Mediator { // 储存同事类集合 private colleagues: Set<Colleague> = new Set<Colleague>(); // 添加未加入的同事并设置中介 register(colleague: Colleague): void { if (!this.colleagues.has(colleague)) { this.colleagues.add(colleague); colleague.setMedium(this); } } // 中介接受请求 relay(colleague: Colleague): void { if (this.colleagues.has(colleague)) { colleague.receive(); } } } // 抽象同事类 abstract class Colleague { protected mediator: Mediator; // 中介对象 protected colleague: Colleague; // 要查询的同事对象 protected phone: string; // 查询内容 constructor(phone: string) { this.phone = phone; } // 设置中介 setMedium(mediator: Mediator): void { this.mediator = mediator; } abstract searchColleague(colleague: Colleague): void; // 查询同事 abstract receive(): void; // 接受请求 abstract send(): void; // 发送请求 } // 具体同事类 class Tom extends Colleague { constructor(phone: string) { super(phone); } searchColleague(colleague: Colleague): void { this.colleague = colleague; } receive(): void { console.log(`Tom 收到请求,,电话号码为${this.phone}`); } send(): void { console.log("Tom 发出电话查询请求"); this.mediator.relay(this.colleague); } } class Jerry extends Colleague { constructor(phone: string) { super(phone); } searchColleague(colleague: Colleague): void { this.colleague = colleague; } receive(): void { console.log(`Jerry 收到请求,电话号码为${this.phone}`); } send(): void { console.log("Jerry 发出电话查询请求"); this.mediator.relay(this.colleague); } } let mediator: Mediator = new ConcreteMediator(); let colleague1: Colleague = new Tom("1234567"); let colleague2: Colleague = new Jerry("2234567"); // 设置相同的中介 mediator.register(colleague1); mediator.register(colleague2); colleague1.searchColleague(colleague2); // Tom 查询 Jerry colleague2.searchColleague(colleague1); // Jerry 查询 Tom colleague1.send(); console.log("--------------------------"); colleague2.send();
备忘录模式:
1、定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,
以便以后当需要时能将该对象恢复到原先保存的状态
2、模型结构:
(1)发起人(Originator):记录当前时刻的内部状态信息,提供创建备忘录和恢复备忘录数据的功能,
实现其他业务功能,它可以访问备忘录里的所有信息
(2)备忘录(Memento):负责存储发起人的内部状态,在需要的时候提供这些内部状态给发起人
(3)管理者(Caretaker):管理备忘录,提供保存与获取备忘录的功能,但其不能对备忘录的内容进行访问与修改