原文:
dev.to:Design Patterns in JavaScript
GitHub:Design Patterns in JavaScript
JS中的设计模式
🚀 什么是设计模式?
设计模式是软件设计领域处理通用问题的解决方案。这些模式是易于重用和具备表现力的。
根据Wikipedia:
在软件工程中,一个软件设计模式是在软件设计中在给定的上下文的情况下,一种通用的、可复用的处理普遍问题的解决方案。这不是可以直接转换成源码或者机器码的最终设计。这是对于如何解决问题,可以适用在不同的情况下的一种描述或者模板。
设计模式的分类
创建型设计模式用于创建对象来替换直接初始化对象。
根据Wikipedia:
在软件工程中,创建型设计模式是处理对象创建机制,试图在某种程度上创建适合当前情况的对象的一种模式。对象创建的基本形式可能导致设计的复杂度或者设计问题。创建型设计模式通过以某种方式控制对象的创建解决了这个问题。
它定义了创建单独对象的接口,并且可以让子类决定初始化哪个类。
根据Wikipedia:
在基于类的编程中,工厂方法模式是创建型设计模式的一种,是使用工厂方法来处理创建对象的问题,不需要指定创建对象的具体类。通过调用工厂方法来创建对象 - 或者通过指定一个接口并且在子类中实现,或者通过基类实现和被衍生类可选的重写,而不是通过调用构造器。
示例:
有一个Point的类,我们要创建 Cartesian point 和 Polar point。定义一个Point工厂来处理。
CoordinateSystem = {CARTESIAN: 0,POLAR: 1,};class Point {constructor(x, y) {this.x = x;this.y = y;}static get factory() {return new PointFactory();}}
定义Point 工厂:
class PointFactory {static newCartesianPoint(x, y) {return new Point(x, y);}static newPolarPoint(rho, theta) {return new Point(rho * Math.cos(theta), rho * Math.sin(theta));}}
如何使用:
let point = PointFactory.newPolarPoint(5, Math.PI/2);let point2 = PointFactory.newCartesianPoint(5, 6)console.log(point);console.log(point2);
抽象工厂(Abstract Factory)
抽象工厂创建一组相同的对象而不需要指定他们的具体类。
根据Wikipedia:
抽象工厂模式提供了一种方式,封装了一组独立的工厂,这些工厂具有相同的主题,而不需要指定他们的具体类。
示例:
Drink示例,
class Drink{consume() {}}class Tea extends Drink{consume() {console.log('This is Tea');}}class Coffee extends Drink{consume(){console.log(`This is Coffee`);}}
Drink工厂:
class DrinkFactory{prepare(amount)}class TeaFactory extends DrinkFactory{makeTea(){console.log(`Tea Created`);return new Tea();}}class CoffeeFactory extends DrinkFactory{makeCoffee(){console.log(`Coffee Created`);return new Coffee();}}
如何使用:
let teaDrinkFactory = new TeaFactory();let tea = teaDrinkFactory.makeTea()tea.consume()
构建者模式 (Builder)
构建者模式是通过简单对象构建复杂对象。
根据Wikipedia:
构建者模式是一种设计模式 ,针对面向对象编程,为多样化的对象创建问题提供了一种灵活的解决方案。
示例:
创建一个Person类,Person类存储了person的一些信息。
class Person {constructor() {this.streetAddress = this.postcode = this.city = "";this.companyName = this.position = "";this.annualIncome = 0;}toString() {return (`Person lives at ${this.streetAddress}, ${this.city}, ${this.postcode}\n` +`and works at ${this.companyName} as a ${this.position} earning ${this.annualIncome}`);}}
现在创建Person``Builder
class PersonBuilder {constructor(person = new Person()) {this.person = person;}get lives() {return new PersonAddressBuilder(this.person);}get works() {return new PersonJobBuilder(this.person);}build() {return this.person;}}
创建PersonJobBuilder类,并且获取Person中job信息。
class PersonJobBuilder extends PersonBuilder {constructor(person) {super(person);}at(companyName) {this.person.companyName = companyName;return this;}asA(position) {this.person.position = position;return this;}earning(annualIncome) {this.person.annualIncome = annualIncome;return this;}}
PersonAddressBuilder将会保持person中address信息。
class PersonAddressBuilder extends PersonBuilder {constructor(person) {super(person);}at(streetAddress) {this.person.streetAddress = streetAddress;return this;}withPostcode(postcode) {this.person.postcode = postcode;return this;}in(city) {this.person.city = city;return this;}}
使用:
let personBuilder = new PersonBuilder();let person = personBuilder.lives.at("ABC Road").in("Multan").withPostcode("66000").works.at("Octalogix").asA("Engineer").earning(10000).build();console.log(person.toString());
原型模式 (Prototype)
通过已有的对象创建新对象。
根据Wikipedia:
原型模式是在软件开发中一种创建型的设计模式。这被用于当对象的创建是由原型实例来决定,用于克隆生成新的对象。
示例:
Car案例:
class Car {constructor(name, model) {this.name = name;this.model = model;}SetName(name) {console.log(`${name}`)}clone() {return new Car(this.name, this.model);}}
如何使用:
let car = new Car();car.SetName('Audi);let car2 = car.clone()car2.SetName('BMW')
单例模式 (Singleton)
单例模式确保了对于一个特定的类只会有一个对象。
根据Wikipedia:
在软件工程中,单例模式是一种设计模式用来限制一个类的初始化只会有一个 ‘single ‘ 实例。当需要在跨系统中协调一些动作只需要一个精确的对象时这是有用的。
示例:
创建一个单例类。
class Singleton {constructor(){const instance = this.constructor.instance;if (instance) {return instance;}this.constructor.instance = this;}say() {console.log('Saying...')}}
如何使用:
let s1 = new Singleton();let s2 = new Singleton();console.log('Are they same? ' + (s1 === s2));s1.say();
结构性设计模式
结构型设计模式是关于类和对象组合的。用继承来组合接口。
根据Wikipedia:
在软件工程中,结构型设计模式是用于减轻设计,通过识别出一种简单的方式,来表达实体之间关系的设计模式。
分类:
- 适配器模式
- 桥接模式
- 组合模式
- 装饰器模式
- 外观模式
- 轻量模式
- 代理模式
适配器模式(Adapter)
适配器模式允许一些拥有不兼容接口的类一起工作,通过已有的类包裹自己的接口。
根据Wikipedia:
在软件工程中,适配器模式是一种软件设计模式用于允许 已有类的接口可以被当做另一种接口使用。这经常被用于已有的类能够与其他的类一起工作而不需要修改源代码。
示例:calculator的示例。Calculator1是老接口,Calculator2是新接口。创建一个适配器,用于包裹新的接口,并且用新的方法返回结果:
class Calculator1 {constructor() {this.operations = function(value1, value2, operation) {switch (operation) {case 'add':return value1 + value2;case 'sub':return value1 - value2;}};}}class Calculator2 {constructor() {this.add = function(value1, value2) {return value1 + value2;};this.sub = function(value1, value2) {return value1 - value2;};}}
创建Adapter类:
class CalcAdapter {constructor() {const cal2 = new Calculator2();this.operations = function(value1, value2, operation) {switch (operation) {case 'add':return cal2.add(value1, value2);case 'sub':return cal2.sub(value1, value2);}};}}
如何使用:
const adaptedCalc = new CalcAdapter();console.log(adaptedCalc.operations(10, 55, 'sub'));
桥接模式(Bridge)
桥接模式用于分离抽象和实现,以便于两者能独立变化。
根据Wikipedia:
桥接模式是一种结构性设计模式,可以让你把一个庞大的类或者一组紧密相关的类分离成两组单独的分类,抽象和实现,这样他们就能彼此单独开发。
示例:
创建一个Renderer类来渲染多种图形:
class VectorRenderer {renderCircle(radius) {console.log(`Drawing a circle of radius ${radius}`);}}class RasterRenderer {renderCircle(radius) {console.log(`Drawing pixels for circle of radius ${radius}`);}}class Shape {constructor(renderer) {this.renderer = renderer;}}class Circle extends Shape {constructor(renderer, radius) {super(renderer);this.radius = radius;}draw() {this.renderer.renderCircle(this.radius);}resize(factor) {this.radius *= factor;}}
如何使用:
let raster = new RasterRenderer();let vector = new VectorRenderer();let circle = new Circle(vector, 5);circle.draw();circle.resize(2);circle.draw();
组合模式(Composite)
组合多个对象以便于他们能作为一个单独的对象来使用。
根据Wikipedia:
组合设计模式描述了一组对象被同样的方式对待,作为同种类型对象的一个实例。
示例:job案例:
class Employer{constructor(name, role){this.name=name;this.role=role;}print(){console.log("name:" +this.name + " relaxTime: " );}}
创建GroupEmployer
class EmployerGroup{constructor(name, composite=[]){console.log(name)this.name=name;this.composites=composite;}print(){console.log(this.name);this.composites.forEach(emp=>{emp.print();})}}
如何使用:
let zee= new Employer("zee","developer")let shan= new Employer("shan","developer")let groupDevelopers = new EmployerGroup( "Developers", [zee,shan] );
装饰器模式(Decorator)
动态的增加或者覆盖对象的行为。
根据Wikipedia:
装饰器模式是一种设计模式允许给单个对象添加行为,动态的,而不会影响来自于同一个类中的其他对象。
示例:
下面有一个Shape类和Circle类,如果要画一个圆,那么就创建一个画圆的方法即可。如果想画一个红色的圆?这时候装饰器模式就可以帮助我们了。
class Shape {constructor(color) {this.color = color;}}class Circle extends Shape {constructor(radius = 0) {super();this.radius = radius;}resize(factor) {this.radius *= factor;}toString() {return `A circle ${this.radius}`;}}
创建一个ColoredShape类:
class ColoredShape extends Shape {constructor(shape, color) {super();this.shape = shape;this.color = color;}toString() {return `${this.shape.toString()}` + `has the color ${this.color}`;}}
如何使用:
let circle = new Circle(2);console.log(circle);let redCircle = new ColoredShape(circle, "red");console.log(redCircle.toString());
外观模式(Facade)
外观模式为复杂代码提供了一种简单接口。
根据Wikipedia:
外观模式是一种经常应用在面向对象编程中的软件设计模式。和建筑的外观类似,一个facade是一个对象作为前置接口,用来隐藏更复杂的潜在的或者结构化的代码。
示例:
下面看一个客户端与计算机交互的例子:
class CPU {freeze() {console.log("Freezed....")}jump(position) { console.log("Go....")}execute() { console.log("Run....") }}class Memory {load(position, data) { console.log("Load....") }}class HardDrive {read(lba, size) { console.log("Read....") }}
创建Facade
class ComputerFacade {constructor() {this.processor = new CPU();this.ram = new Memory();this.hd = new HardDrive();}start() {this.processor.freeze();this.ram.load(this.BOOT_ADDRESS, this.hd.read(this.BOOT_SECTOR, this.SECTOR_SIZE));this.processor.jump(this.BOOT_ADDRESS);this.processor.execute();}}
如何使用:
let computer = new ComputerFacade();computer.start();
轻量模式(Flyweight)
轻量模式用于减轻创建同样对象的内存消耗。
根据Wikipedia:
轻量模式是一个对象用于减少内存的使用,通过与类似的对象尽可能多的共享数据。
示例:
看一个user的案例。假设有多个user拥有同一name。我们可以通过存储name来节约内存和给所有有同样们名字的user一个引用。
class User{constructor(fullName){this.fullName = fullName;}}class User2{constructor(fullName){let getOrAdd = function(s){let idx = User2.strings.indexOf(s);if (idx !== -1) return idx;else{User2.strings.push(s);return User2.strings.length - 1;}};this.names = fullName.split(' ').map(getOrAdd);}}User2.strings = [];function getRandomInt(max) {return Math.floor(Math.random() * Math.floor(max));}let randomString = function(){let result = [];for (let x = 0; x < 10; ++x)result.push(String.fromCharCode(65 + getRandomInt(26)));return result.join('');};
接下来通过创建10k对象,对比下使用轻量和不使用轻量的内存消耗。
let users = [];let users2 = [];let firstNames = [];let lastNames = [];for (let i = 0; i < 100; ++i){firstNames.push(randomString());lastNames.push(randomString());}// making 10k usersfor (let first of firstNames)for (let last of lastNames) {users.push(new User(`${first} ${last}`));users2.push(new User2(`${first} ${last}`));}console.log(`10k users take up approx ` +`${JSON.stringify(users).length} chars`);let users2length =[users2, User2.strings].map(x => JSON.stringify(x).length).reduce((x,y) => x+y);console.log(`10k flyweight users take up approx ` +`${users2length} chars`);
代理模式(Proxy)
通过使用代理,一个类可以体现另一个类的功能。
根据Wikipedia:
代理模式是一种软件设计模式。一个代理,他最通用的形式,是一个类,对其他的东西起一个接口的作用。
示例:
看一个value代理的例子。
class Percentage {constructor(percent) {this.percent = percent;}toString() {return `${this.percent}&`;}valueOf() {return this.percent / 100;}}
如何使用:
let fivePercent = new Percentage(5);console.log(fivePercent.toString());console.log(`5% of 50 is ${50 * fivePercent}`);
行为型设计模式
行为型模式是专门关于或者涉及对象之间通信的模式。
根据Wikipedia:
在软件工程中,行为型设计模式是用于对象间识别通用通信模式的设计模式。通过应用这些模式,在执行对象间通信时可以提升灵活性。
- 责任链模式
- 命令模式
- 迭代器模式
- 中介者模式
- 备忘录模式
- 观察者
- 访问者
- 策略模式
- 状态模式
- 模板方法
责任链模式(Chain of Responsibility)
责任链创建对象链。从一个点开始,直到它发现一个特定的条件后停止。
根据Wikipedia:
在面向对象设计,责任链模式包含了命令对象的来源和一系列的处理运算对象。
示例:
我们创建一个带有creature的游戏的例子。creature将会提升他的防护性,当他到达一个特定的点的时候将会攻击。创建一个链,或者攻击或者防护。
class Creature {constructor(name, attack, defense) {this.name = name;this.attack = attack;this.defense = defense;}toString() {return `${this.name} (${this.attack}/${this.defense})`;}}class CreatureModifier {constructor(creature) {this.creature = creature;this.next = null;}add(modifier) {if (this.next) this.next.add(modifier);else this.next = modifier;}handle() {if (this.next) this.next.handle();}}class NoBonusesModifier extends CreatureModifier {constructor(creature) {super(creature);}handle() {console.log("No bonuses for you!");}}
加强攻击:
class DoubleAttackModifier extends CreatureModifier {constructor(creature) {super(creature);}handle() {console.log(`Doubling ${this.creature.name}'s attack`);this.creature.attack *= 2;super.handle();}}
加强防护:
class IncreaseDefenseModifier extends CreatureModifier {constructor(creature) {super(creature);}handle() {if (this.creature.attack <= 2) {console.log(`Increasing ${this.creature.name}'s defense`);this.creature.defense++;}super.handle();}}
使用:
let peekachu = new Creature("Peekachu", 1, 1);console.log(peekachu.toString());let root = new CreatureModifier(peekachu);root.add(new DoubleAttackModifier(peekachu));root.add(new IncreaseDefenseModifier(peekachu));root.handle();console.log(peekachu.toString());
命令模式(Command)
创建对象并且封装对象中行为的模式。
根据Wikipedia:
在面向对象编程中,命令模式是一种行为设计模式,一个对象封装了所有的信息,并在稍后需要执行一个动作或者触发一个事件。这些信息包括方法名称,以及拥有方法和方法参数值的对象。
示例:
举一个银行账户的例子,当我们要存取一定数量的钱时,就发出一个命令。
class BankAccount {constructor(balance = 0) {this.balance = balance;}deposit(amount) {this.balance += amount;console.log(`Deposited ${amount} Total balance ${this.balance}`);}withdraw(amount) {if (this.balance - amount >= BankAccount.overdraftLimit) {this.balance -= amount;console.log("Widhdrawn");}}toString() {return `Balance ${this.balance}`;}}BankAccount.overdraftLimit = -500;let Action = Object.freeze({deposit: 1,withdraw: 2,});
创建命令:
class BankAccountCommand {constructor(account, action, amount) {this.account = account;this.action = action;this.amount = amount;}call() {switch (this.action) {case Action.deposit:this.account.deposit(this.amount);break;case Action.withdraw:this.account.withdraw(this.amount);break;}}undo() {switch (this.action) {case Action.deposit:this.account.withdraw(this.amount);break;case Action.withdraw:this.account.deposit(this.amount);break;}}}
如何使用:
let bankAccount = new BankAccount(100);let cmd = new BankAccountCommand(bankAccount, Action.deposit, 50);cmd.call();console.log(bankAccount.toString());cmd.undo();console.log(bankAccount.toString());
迭代器(Iterator)
迭代器访问对象中的元素而不需要暴露潜藏在下面的表现。
根据Wikipedia:
在面向对象编程中,迭代器模式是一种设计模式指的是一个迭代器用于遍历一个容器,并且访问容器中的元素。
示例:
举一个打印数组中打印值的例子,并用迭代器倒序打印。
class Stuff{constructor(){this.a = 11;this.b = 22;}[Symbol.iterator](){let i = 0;let self = this;return {next: function(){return {done: i > 1,value: self[i++ === 0 ? 'a' : 'b']};}}}get backwards(){let i = 0;let self = this;return {next: function(){return {done: i > 1,value: self[i++ === 0 ? 'b' : 'a']};},// make iterator iterable[Symbol.iterator]: function() { return this; }}}}
如何使用:
let values = [100, 200, 300];for (let i in values){console.log(`Element at pos ${i} is ${values[i]}`);}for (let v of values){console.log(`Value is ${v}`);}let stuff = new Stuff();for (let item of stuff)console.log(`${item}`);for (let item of stuff.backwards)console.log(`${item}`);
中介者模式(Mediator)
中介者模式是添加第三方对象用来控制两个对象的交互。它允许类之间的松散耦合,并成为拥有方法细节的唯一的类。
根据Wikipedia:
中介者模式定义了一个对象,这个对象封装了一组对象是如何交互的。这个模式被认为是行为模式是由于它可以改变程序运行行为的方式。在面向对象中,程序通常有很多的类组成。
示例:
举一个person使用chat room的例子。这里的chatroom扮演了中介者的角色,用于两个人之间的通信。
class Person {constructor(name) {this.name = name;this.chatLog = [];}receive(sender, message) {let s = `${sender}: '${message}'`;console.log(`[${this.name}'s chat session] ${s}`);this.chatLog.push(s);}say(message) {this.room.broadcast(this.name, message);}pm(who, message) {this.room.message(this.name, who, message);}}
创建ChatRoom:
class ChatRoom {constructor() {this.people = [];}broadcast(source, message) {for (let p of this.people)if (p.name !== source) p.receive(source, message);}join(p) {let joinMsg = `${p.name} joins the chat`;this.broadcast("room", joinMsg);p.room = this;this.people.push(p);}message(source, destination, message) {for (let p of this.people)if (p.name === destination) p.receive(source, message);}}
如何使用:
let room = new ChatRoom();let zee = new Person("Zee");let shan = new Person("Shan");room.join(zee);room.join(shan);zee.say("Hello!!");let doe = new Person("Doe");room.join(doe);doe.say("Hello everyone!");
备忘录模式(Memento)
备忘录模式是恢复一个对象之前状态。
根据Wikipedia:
备忘录模式是一种软件设计模式提供了一种恢复一个对象之前状态的能力。备忘录模式有三个对象实现:发起者,守护者和记录者
示例:
举一个银行账户的例子,我们保存之前的状态,和撤回的功能。
class Memento {constructor(balance) {this.balance = balance;}}
添加银行账户:
class BankAccount {constructor(balance = 0) {this.balance = balance;}deposit(amount) {this.balance += amount;return new Memento(this.balance);}restore(m) {this.balance = m.balance;}toString() {return `Balance: ${this.balance}`;}}
如何使用:
let bankAccount = new BankAccount(100);let m1 = bankAccount.deposit(50);console.log(bankAccount.toString());// restore to m1bankAccount.restore(m1);console.log(bankAccount.toString());
观察者模式(Observer)
观察者模式允许一些观察对象看到一个事件。
根据Wikipedia:
观察者模式是一种软件设计模式,有一个主题对象,一个具体对象,维护了一组依赖清单,叫做观察者,自动的提醒状态的变化,通常是调用它们其中的一个方法。
示例:
举一个person的例子,当person生病了,会显示一个提醒。
class Event {constructor() {this.handlers = new Map();this.count = 0;}subscribe(handler) {this.handlers.set(++this.count, handler);return this.count;}unsubscribe(idx) {this.handlers.delete(idx);}fire(sender, args) {this.handlers.forEach((v, k) => v(sender, args));}}class FallsIllArgs {constructor(address) {this.address = address;}}class Person {constructor(address) {this.address = address;this.fallsIll = new Event();}catchCold() {this.fallsIll.fire(this, new FallsIllArgs(this.address));}}
如何使用:
let person = new Person("ABC road");let sub = person.fallsIll.subscribe((s, a) => {console.log(`A doctor has been called ` + `to ${a.address}`);});person.catchCold();person.catchCold();person.fallsIll.unsubscribe(sub);person.catchCold();
访问者模式(Visitor)
访问者模式是给对象添加操作而不需要修改这些对象。
根据Wikipedia:
访问者设计模式是一种将算法从操作的对象结构中分离出来的方法。这种分离一个实用的结果就是给已有的对象结构添加新的操作而不需要修改结构的能力。
示例:
举一个 NumberExpression的例子。
class NumberExpression{constructor(value){this.value = value;}print(buffer){buffer.push(this.value.toString());}}
创建AdditionExpression:
class AdditionExpression{constructor(left, right){this.left = left;this.right = right;}print(buffer){buffer.push('(');this.left.print(buffer);buffer.push('+');this.right.print(buffer);buffer.push(')');}}
如何使用:
// 5 + (1+9)let e = new AdditionExpression(new NumberExpression(5),new AdditionExpression(new NumberExpression(1),new NumberExpression(9)));let buffer = [];e.print(buffer);console.log(buffer.join(''));
策略模式(Strategy)
策略模式允许在特定的情况下选择其中的一种算法。
根据Wikipedia:
策略模式是一种软件行为设计模式允许在运行时选择一种设计模式。除了直接实现单一的一个设计模式,代码接收到运行时的指令来决定一组算法里面选择哪一个来使用。
示例:
举个例子,关于文字处理器,基于哪种策略(HTML or Markdown)来显示数据。
let OutputFormat = Object.freeze({markdown: 0,html: 1,});class ListStrategy {start(buffer) {}end(buffer) {}addListItem(buffer, item) {}}class MarkdownListStrategy extends ListStrategy {addListItem(buffer, item) {buffer.push(` * ${item}`);}}class HtmlListStrategy extends ListStrategy {start(buffer) {buffer.push("<ul>");}end(buffer) {buffer.push("</ul>");}addListItem(buffer, item) {buffer.push(` <li>${item}</li>`);}}
创建TextProcessor
class TextProcessor {constructor(outputFormat) {this.buffer = [];this.setOutputFormat(outputFormat);}setOutputFormat(format) {switch (format) {case OutputFormat.markdown:this.listStrategy = new MarkdownListStrategy();break;case OutputFormat.html:this.listStrategy = new HtmlListStrategy();break;}}appendList(items) {this.listStrategy.start(this.buffer);for (let item of items) this.listStrategy.addListItem(this.buffer, item);this.listStrategy.end(this.buffer);}clear() {this.buffer = [];}toString() {return this.buffer.join("\n");}}
如何使用:
let tp = new TextProcessor();tp.setOutputFormat(OutputFormat.markdown);tp.appendList(["one", "two", "three"]);console.log(tp.toString());tp.clear();tp.setOutputFormat(OutputFormat.html);tp.appendList(["one", "two", "three"]);console.log(tp.toString());
状态模式(State)
状态模式是当对象内部状态改变了就修改对象的行为。
根据Wikipedia:
状态模式是一种行为型软件设计模式允许当对象的内部状态改变时修改它的行为。这种模式接近于有限状态机的概念。
示例:
举一个电灯开关的例子,当开关电灯时,它的状态变化。
class Switch {constructor() {this.state = new OffState();}on() {this.state.on(this);}off() {this.state.off(this);}}class State {constructor() {if (this.constructor === State) throw new Error("abstract!");}on(sw) {console.log("Light is already on.");}off(sw) {console.log("Light is already off.");}}
创建状态类:
class OnState extends State {constructor() {super();console.log("Light turned on.");}off(sw) {console.log("Turning light off...");sw.state = new OffState();}}class OffState extends State {constructor() {super();console.log("Light turned off.");}on(sw) {console.log("Turning light on...");sw.state = new OnState();}}
如何使用:
let switch = new Switch();switch.on();switch.off();
模板方法模式(Template Method)
模板方法模式将算法的框架定义为一个抽象类,以及他应该是如何执行的。
根据Wikipedia:
模板方法是在超类中的一个方法,通常是一个抽象超类,按照一些高级的步骤定义了一个操作的框架。
示例:
举一个chess游戏的例子:
class Game {constructor(numberOfPlayers) {this.numberOfPlayers = numberOfPlayers;this.currentPlayer = 0;}run() {this.start();while (!this.haveWinner) {this.takeTurn();}console.log(`Player ${this.winningPlayer} wins.`);}start() {}get haveWinner() {}takeTurn() {}get winningPlayer() {}}
创建chess类:
class Chess extends Game {constructor() {super(2);this.maxTurns = 10;this.turn = 1;}start() {console.log(`Starting a game of chess with ${this.numberOfPlayers} players.`);}get haveWinner() {return this.turn === this.maxTurns;}takeTurn() {console.log(`Turn ${this.turn++} taken by player ${this.currentPlayer}.`);this.currentPlayer = (this.currentPlayer + 1) % this.numberOfPlayers;}get winningPlayer() {return this.currentPlayer;}}
如何使用:
let chess = new Chess();chess.run();

