3.7 代理模式
// 静态代理 interface Subject { doOperation() : void; } class RealSubject implements Subject { public doOperation() { console.log('我是RealSubject类,正在执行'); } } class MyProxy implements Subject { private target : Subject; constructor(realSubject : Subject) { this.target = realSubject; } public doOperation() { console.log('我是代理类'); this.target.doOperation(); } } function main() { const realSubject : Subject = new RealSubject(); const myProxy : Subject = new MyProxy(realSubject); myProxy.doOperation(); } main();
// 动态代理 interface Subject { doOperation() : void; } class RealSubject implements Subject { constructor() {} public doOperation() : void { console.log('我是RealSubject类,正在执行'); } } class ProxyFactory { private target : any; constructor(target : any) { this.target = target; } public getProxyInstance() : any { return new Proxy(this.target, { get: (target, propKey) => { // 做的一些拦截处理 return target[propKey]; } }); } } function main() { const target : Subject = new RealSubject(); const proxyInstance : Subject = <Subject>new ProxyFactory(target).getProxyInstance(); proxyInstance.doOperation(); } main();
四、行为型模式
行为型模式包含模板方法模式、命令模式、访问者模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式(Interpreter模式)、状态模式、策略模式、职责链模式(责任链模式)。行为型模式对在不同的对象之间划分责任和算法的抽象化,行为型模式不仅仅关注类和对象的结构,而且重点关注他们之间的相互作用,通过行为型模式,可以更加清晰地划分类与对象的职责,并研究系统在运行时实例对象之间的交互。
4.1 模板方法模式
abstract class AbstractClass { constructor() {} // 模板方法 public template() : void { this.operation1(); this.hookMethod() && this.operation2(); this.operation3(); } // 基本方法 protected operation1() : void { console.log('使用了方法operation1'); } protected operation2() : void { console.log('使用了方法operation2'); } protected operation3() : void { console.log('使用了方法operation3'); } // 钩子方法 protected hookMethod() : boolean { return true; } } class ConcreteClassA extends AbstractClass { protected operation2() :void { console.log('对该方法operation2进行了修改再使用'); } protected operation3() :void { console.log('对该方法operation3进行了修改再使用'); } } class ConcreteClassB extends AbstractClass { // 覆盖钩子方法 protected hookMethod() : boolean { return false; } } function main() { const class1 : AbstractClass = new ConcreteClassA(); const class2 : AbstractClass = new ConcreteClassB(); class1.template(); class2.template(); } main();
4.2 命令模式
interface Command { execute() : void; undo() : void; } // 开启命令 class ConcreteCommandOn implements Command { private receiver : Receiver; constructor(receiver : Receiver) { this.receiver = receiver; } // 执行命令的方法 public execute() : void { this.receiver.actionOn(); } // 撤销命令的方法 public undo() : void { this.receiver.actionOff(); } } // 关闭命令 class ConcreteCommandOff implements Command { private receiver : Receiver; constructor(receiver : Receiver) { this.receiver = receiver; } // 执行命令的方法 public execute() : void { this.receiver.actionOff(); } // 撤销命令的方法 public undo() : void { this.receiver.actionOn(); } } // 空命令(省去判空操作) class NoCommand implements Command { public execute() : void {} public undo() : void {} } class Receiver { public actionOn() : void { console.log('我是命令接收者,开启了某动作'); } public actionOff() : void { console.log('我是命令接收者,关闭了某动作'); } } class Invoker { private onCommands : Array<Command>; private offCommands : Array<Command>; private undoCommand : Command; private slotNum : number = 7; constructor() { this.undoCommand = new NoCommand(); this.onCommands = []; this.offCommands = []; for (let i = 0; i < this.slotNum; i++) { this.onCommands[i] = new NoCommand(); this.offCommands[i] = new NoCommand(); } } public setCommand(index : number, onCommand : Command, offCommand : Command) : void { this.onCommands[index] = onCommand; this.offCommands[index] = offCommand; } // 开启 public on (index : number) : void { this.onCommands[index].execute();// 调用相应方法 //记录这次操作,用于撤销 this.undoCommand = this.onCommands[index]; } // 关闭 public off (index : number) : void { this.offCommands[index].execute(); this.undoCommand = this.offCommands[index]; } // 撤销 public undo () : void { this.undoCommand.undo(); } } function main() { // 创建接收者 const receiver : Receiver = new Receiver(); // 创建命令 const commandOn : Command = new ConcreteCommandOn(receiver); const commandOff : Command = new ConcreteCommandOff(receiver); // 创建调用者 const invoker : Invoker = new Invoker(); invoker.setCommand(0, commandOn, commandOff); invoker.on(0); invoker.off(0); invoker.undo(); } main();
4.3 访问者模式
abstract class AbstractElement { // 定义业务逻辑 public abstract doSomething() : void; // 允许谁来访问 public abstract accept (visitor : Visitor) : void; } class ConcreteElement1 extends AbstractElement{ public doSomething() : void { console.log('ConcreteElement1执行的业务逻辑'); } public accept(visitor : Visitor) : void { visitor.visit1(this) } } class ConcreteElement2 extends AbstractElement{ public doSomething() : void { console.log('ConcreteElement1执行的业务逻辑'); } public accept(visitor : Visitor) : void { visitor.visit2(this) } } abstract class Visitor { public abstract visit1(element1 : ConcreteElement1) : void; public abstract visit2(element2 : ConcreteElement2) : void; } class ConcreteVistor extends Visitor { public visit1(element1 : ConcreteElement1) : void { console.log('进入处理element1') element1.doSomething(); } public visit2(element2 : ConcreteElement2) : void { console.log('进入处理element2'); element2.doSomething(); } } // 数据结构,管理很多元素(ConcreteElement1,ConcreteElement1) class ObjectStructure { private listSet : Set<AbstractElement>; constructor() { this.listSet = new Set(); } // 增加 public attach(element : AbstractElement) : void { this.listSet.add(element); } // 删除 public detach(element : AbstractElement) : void { this.listSet.delete(element); } // 显示 public display(visitor : Visitor) : void { for (let element of this.listSet.values()) { element.accept(visitor); } } } function main() { const objectStructure : ObjectStructure = new ObjectStructure(); objectStructure.attach(new ConcreteElement1()); objectStructure.attach(new ConcreteElement2()); const visitor :Visitor = new ConcreteVistor(); objectStructure.display(visitor); } main();
4.4 迭代器模式
interface AbstractIterator { next() : any; hasNext() : boolean; remove() : boolean; } class ConcreteIterator implements AbstractIterator { private list : any[]; public cursor : number = 0; constructor(array : any[]) { this.list = array; } public next() : any { return this.hasNext() ? this.list[this.cursor++] : null; } public hasNext() : boolean { return this.cursor < this.list.length; } public remove() : boolean{ this.list.splice(this.cursor--, 1); return true; } } interface Aggregate { add(value : any) : void; remove(value : any) : void; createIterator() : AbstractIterator; } class ConcreteAggregate implements Aggregate { // 容纳对象的容器 private list : any[]; constructor() { this.list = []; } add(value : any) : void { this.list.push(value) } remove(value : any) : void { const index = this.list.findIndex((listValue) => { return value === listValue; }); this.list.splice(index, 1); } createIterator() : AbstractIterator { return new ConcreteIterator(this.list); } } function main() { const aggregate : Aggregate = new ConcreteAggregate(); aggregate.add('11111'); aggregate.add('222222'); const iterator : AbstractIterator = aggregate.createIterator(); while(iterator.hasNext()) { console.log(iterator.next()); } } main();
4.5 观察者模式
// 观察者模式 interface AbstractSubject { registerObserver(observer : Observer) : void; remove(observer : Observer) : void; notifyObservers() : void; } class ConcreteSubject implements AbstractSubject { private observers : Array<Observer>; constructor() { this.observers = []; } public registerObserver(observer : Observer) : void { this.observers.push(observer); }; public remove(observer : Observer) : void { const observerIndex = this.observers.findIndex(value => { return value == observer; }) observerIndex >= 0 && this.observers.splice(observerIndex, 1); }; public notifyObservers() : void { this.observers.forEach(observer => observer.update()) }; } interface Observer { update() : void; } class ConcreteObserver1 implements Observer { public update() : void { console.log('已经执行更新操作1,值为'); } } class ConcreteObserver2 implements Observer { public update() : void { console.log('已经执行更新操作2,值为'); } } function main() { const subject : AbstractSubject = new ConcreteSubject(); const observer1 : Observer = new ConcreteObserver1(); const observer2 : Observer = new ConcreteObserver2(); subject.registerObserver(observer1); subject.registerObserver(observer2); subject.notifyObservers(); } main();
// 发布订阅模式 interface Publish { registerObserver(eventType : string, subscribe : Subscribe) : void; remove(eventType : string, subscribe ?: Subscribe) : void; notifyObservers(eventType : string) : void; } interface SubscribesObject{ [key : string] : Array<Subscribe> } class ConcretePublish implements Publish { private subscribes : SubscribesObject; constructor() { this.subscribes = {}; } registerObserver(eventType : string, subscribe : Subscribe) : void { if (!this.subscribes[eventType]) { this.subscribes[eventType] = []; } this.subscribes[eventType].push(subscribe); } remove(eventType : string, subscribe ?: Subscribe) : void { const subscribeArray = this.subscribes[eventType]; if (subscribeArray) { if (!subscribe) { delete this.subscribes[eventType]; } else { for (let i = 0; i < subscribeArray.length; i++) { if (subscribe === subscribeArray[i]) { subscribeArray.splice(i, 1); } } } } } notifyObservers(eventType : string, ...args : any[]) : void { const subscribes = this.subscribes[eventType]; if (subscribes) { subscribes.forEach(subscribe => subscribe.update(...args)) } } } interface Subscribe { update(...value : any[]) : void; } class ConcreteSubscribe1 implements Subscribe { public update(...value : any[]) : void { console.log('已经执行更新操作1,值为', ...value); } } class ConcreteSubscribe2 implements Subscribe { public update(...value : any[]) : void { console.log('已经执行更新操作2,值为', ...value); } } function main() { const publish = new ConcretePublish(); const subscribe1 = new ConcreteSubscribe1(); const subscribe2 = new ConcreteSubscribe2(); publish.registerObserver('1', subscribe1); publish.registerObserver('2', subscribe2); publish.notifyObservers('2', '22222'); } main();
4.6 中介者模式
abstract class Colleague { public abstract onEvent(eventType : string) : void; } class ConcreteColleagueA extends Colleague{ private mediator : Mediator; constructor(mediator : Mediator) { super(); this.mediator = mediator; } public onEvent(eventType : string) : void { this.mediator.doEvent(eventType); } // 自己的一些事情 public doSomething() : void { console.log('A被运行了'); } } class ConcreteColleagueB extends Colleague { private mediator : Mediator; constructor(mediator : Mediator) { super(); this.mediator = mediator; } public onEvent(eventType : string) : void { this.mediator.doEvent(eventType); } // 自己的一些事情 public doSomething() : void { console.log('B被运行了'); } } abstract class Mediator { protected _colleagueA ?: ConcreteColleagueA; protected _colleagueB ?: ConcreteColleagueB; set colleagueA(colleagueA : ConcreteColleagueA) { this._colleagueA = colleagueA; } set colleagueB(colleagueB : ConcreteColleagueB) { this._colleagueB = colleagueB; } public abstract doEvent(eventType : string) : void; } class ConcreteMediator extends Mediator { //1. 根据得到消息,完成对应任务 //2. 中介者在这个方法,协调各个具体的同事对象,完成任务 public doEvent(eventType : string) : void { switch (eventType) { case "A": { this.doColleagueAEvent(); break; } case "B": { this.doColleagueBEvent(); break; } default: { } } } // 相应业务逻辑 public doColleagueAEvent() : void { super._colleagueA && super._colleagueA.doSomething(); super._colleagueB && super._colleagueB.doSomething(); console.log('A-B执行完毕'); } public doColleagueBEvent() : void { super._colleagueB && super._colleagueB.doSomething(); super._colleagueA && super._colleagueA.doSomething(); console.log('B-A执行完毕'); } } function main() { const mediator : Mediator = new ConcreteMediator(); const myColleagueA : ConcreteColleagueA = new ConcreteColleagueA(mediator); const myColleagueB : ConcreteColleagueB = new ConcreteColleagueB(mediator); mediator.colleagueA = myColleagueA; mediator.colleagueB = myColleagueB; myColleagueA.onEvent('A'); myColleagueB.onEvent('B'); } main();
4.7 备忘录模式
class Originator { private _state : string = ''; constructor() {} get state() { return this._state; } set state(value) { this._state = value; } // 创建一个备忘录 public createMemento() : Memento { console.log('创建了一个备忘录!'); return new Memento(this._state); } // 恢复一个备忘录 public recoverMemento(memento : Memento) { console.log('恢复了一个备忘录!'); this.state = memento.state; } } class Memento { private _state : string; constructor(state : string) { this._state = state; } get state() : string { return this._state; } } class Caretaker { // 保存一次状态用此,保存多次用数组 private memento ?: Memento; public getMemento() : Memento | undefined { return this.memento; } public setMemento(memento : Memento) { this.memento = memento; } } function main() { // 定义发起人 const originator : Originator = new Originator(); // 定义守护者 const caretaker : Caretaker = new Caretaker(); // 创建一个备忘录 const memento : Memento = originator.createMemento(); // 将备忘录存储到守护者 caretaker.setMemento(memento); // 恢复一个备忘录 originator.recoverMemento(memento); } main();
4.8 解释器模式
// 以下是一个规则检验器实现,具有 and 和 or 规则,通过规则可以构建一颗解析树,用来检验一个文本是否满足解析树定义的规则。 // 例如一颗解析树为 D And (A Or (B C)),文本 "D A" 满足该解析树定义的规则 abstract class Expression { public abstract interpreter(str : string) : boolean; } class TerminalExpression extends Expression { private literal : string; constructor(str : string) { super(); this.literal = str; } public interpreter(str : string) : boolean { for (let charVal of str) { if (charVal === this.literal) { return true; } } return false; } } class AndExpression extends Expression { private expression1 : Expression; private expression2 : Expression; constructor(expression1 : Expression, expression2 : Expression) { super(); this.expression1 = expression1; this.expression2 = expression2; } public interpreter(str : string) : boolean { return this.expression1.interpreter(str) && this.expression2.interpreter(str); } } class OrExpression extends Expression { private expression1 : Expression; private expression2 : Expression; constructor(expression1 : Expression, expression2 : Expression) { super(); this.expression1 = expression1; this.expression2 = expression2; } public interpreter(str : string) : boolean { return this.expression1.interpreter(str) || this.expression2.interpreter(str); } } function buildInterpreterTree() { const terminal1 : Expression = new TerminalExpression('A'); const terminal2 : Expression = new TerminalExpression('B'); const terminal3 : Expression = new TerminalExpression('C'); const terminal4 : Expression = new TerminalExpression('D'); // B And C const alternation1 : Expression = new AndExpression(terminal2, terminal3); // A Or (B C) const alternation2 : Expression = new OrExpression(terminal1, alternation1); // D And (A Or (B C)) return new AndExpression(terminal4, alternation2); } function main() { const define : Expression = buildInterpreterTree(); const context1 : string = "D A"; const context2 : string = "D B C"; console.log(define.interpreter(context1)); console.log(define.interpreter(context2)); } main();
4.9 状态模式
abstract class State { public abstract handle1() : void; public abstract handle2() : void; } class ConcreteState1 extends State { private context : Context; constructor(context : Context) { super(); this.context = context; } // 本状态下需要处理的逻辑 public handle1() : void { console.log('State1的状态需要处理的逻辑'); } // 将进行状态转移 public handle2() : void { this.context.currentState = this.context.STATE2; console.log('由状态state1转为state2'); } } class ConcreteState2 extends State { private context : Context; constructor(context : Context) { super(); this.context = context; } // 进行状态转移 public handle1() : void { this.context.currentState = this.context.STATE1; console.log('由状态state2转为state1'); } // 本状态下的处理逻辑 public handle2() : void { console.log('State2的状态需要处理的逻辑'); } } class Context { public STATE1 : State = new ConcreteState1(this); public STATE2 : State = new ConcreteState2(this); public currentState : State; constructor() { this.currentState = this.STATE1; } public doOperation1() { this.currentState?.handle2(); } public doOperation2() { this.currentState?.handle1(); } } function main() { const context : Context = new Context(); context.doOperation1(); context.doOperation2(); } main();
4.10 策略模式
interface Strategy { // 策略模式运算法则 doSomething() : void; } class ConcreteStrategy1 implements Strategy { public doSomething() : void { console.log('使用的策略1'); } } class ConcreteStrategy2 implements Strategy { public doSomething() : void { console.log('使用的策略2'); } } class ContextofStrategy { private _strategy : Strategy; constructor(strategy : Strategy) { this._strategy = strategy; } set strategy(strategy : Strategy) { this._strategy = strategy; } //封装后的策略方法 doOperation() : void { this._strategy.doSomething(); } } function main() { const strategy1 : Strategy = new ConcreteStrategy1(); const strategy2 : Strategy = new ConcreteStrategy2(); const context : ContextofStrategy = new ContextofStrategy(strategy1); context.doOperation(); context.strategy = strategy2; context.doOperation(); } main();
4.11 职责链模式
abstract class Handler { // 下一个处理者 public successor ?: Handler; public name : string; constructor(name : string) { this.name = name; } public abstract handleRequest(request : MyRequest) : void; public setNext(successor : Handler) : void { this.successor = successor; } } class ConcreteHandler1 extends Handler { constructor(name : string) { super(name); } public handleRequest (request : MyRequest) : void { // 首先判断当前级别是否能够处理,不能够处理则交给下一个级别处理 if (request.level <= 1) { console.log('被一级处理'); } else { // 交给下一级处理 this.successor && this.successor.handleRequest(request); } } } class ConcreteHandler2 extends Handler { constructor(name : string) { super(name); } public handleRequest (request : MyRequest) : void { // 首先判断当前级别是否能够处理,不能够处理则交给下一个级别处理 if (request.level > 1 && request.level <= 2) { console.log('被二级处理'); } else { // 交给下一级处理 this.successor && this.successor.handleRequest(request); } } } class ConcreteHandler3 extends Handler { constructor(name : string) { super(name); } public handleRequest (request : MyRequest) : void { // 首先判断当前级别是否能够处理,不能够处理则交给下一个级别处理 if (request.level > 2) { console.log('被三级处理'); } else { // 交给下一级处理 this.successor && this.successor.handleRequest(request); } } } class MyRequest { private _level : number; constructor(level : number) { this._level = level; } get level() : number { return this._level; } set level(value : number) { this._level = this.level; } } function main() { // 创建一个请求 const request : MyRequest = new MyRequest(5); // 创建相关处理人 const handler1 : Handler = new ConcreteHandler1('lili'); const handler2 : Handler = new ConcreteHandler2('linlin'); const handler3 : Handler = new ConcreteHandler3('shunshun'); // 设置下级别审批,构成环形结构 handler1.setNext(handler2); handler2.setNext(handler3); handler3.setNext(handler1); handler1.handleRequest(request); } main();