├── assets ├── proxy.png ├── Iterator.png ├── banner.png ├── facade.png ├── factory.png ├── mediator.png ├── observer.png ├── strategy.png ├── singleton.png └── visitor.svg ├── iterator.js ├── singleton.js ├── facede.js ├── visitor.js ├── Range.js ├── observer.js ├── mediator.js ├── factory.js ├── momento.js ├── proxy.js ├── strategy.js └── readme.md /assets/proxy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/proxy.png -------------------------------------------------------------------------------- /assets/Iterator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/Iterator.png -------------------------------------------------------------------------------- /assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/banner.png -------------------------------------------------------------------------------- /assets/facade.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/facade.png -------------------------------------------------------------------------------- /assets/factory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/factory.png -------------------------------------------------------------------------------- /assets/mediator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/mediator.png -------------------------------------------------------------------------------- /assets/observer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/observer.png -------------------------------------------------------------------------------- /assets/strategy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/strategy.png -------------------------------------------------------------------------------- /assets/singleton.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MudOnTire/frontend-design-patterns/HEAD/assets/singleton.png -------------------------------------------------------------------------------- /iterator.js: -------------------------------------------------------------------------------- 1 | const item = [1, 'red', false, 3.14]; 2 | 3 | function Iterator(items) { 4 | this.items = items; 5 | this.index = 0; 6 | } 7 | 8 | Iterator.prototype = { 9 | hasNext: function () { 10 | return this.index < this.items.length; 11 | }, 12 | next: function () { 13 | return this.items[this.index++]; 14 | } 15 | } 16 | 17 | const iterator = new Iterator(item); 18 | 19 | while(iterator.hasNext()){ 20 | console.log(iterator.next()); 21 | } -------------------------------------------------------------------------------- /singleton.js: -------------------------------------------------------------------------------- 1 | const FooServiceSingleton = (function () { 2 | function FooService() {} 3 | 4 | let fooService; 5 | 6 | return { 7 | getInstance: function () { 8 | if (!fooService) { 9 | fooService = new FooService(); 10 | } 11 | return fooService; 12 | } 13 | } 14 | })(); 15 | 16 | const fooService1 = FooServiceSingleton.getInstance(); 17 | const fooService2 = FooServiceSingleton.getInstance(); 18 | 19 | console.log(fooService1 === fooService2); -------------------------------------------------------------------------------- /facede.js: -------------------------------------------------------------------------------- 1 | // 绑定事件 2 | function addEvent(element, event, handler) { 3 | if (element.addEventListener) { 4 | element.addEventListener(event, handler, false); 5 | } else if (element.attachEvent) { 6 | element.attachEvent('on' + event, handler); 7 | } else { 8 | element['on' + event] = fn; 9 | } 10 | } 11 | 12 | // 取消绑定 13 | function removeEvent(element, event, handler) { 14 | if (element.removeEventListener) { 15 | element.removeEventListener(event, handler, false); 16 | } else if (element.detachEvent) { 17 | element.detachEvent('on' + event, handler); 18 | } else { 19 | element['on' + event] = null; 20 | } 21 | } -------------------------------------------------------------------------------- /visitor.js: -------------------------------------------------------------------------------- 1 | function Employee(name, salary) { 2 | this.name = name; 3 | this.salary = salary; 4 | } 5 | 6 | Employee.prototype = { 7 | getSalary: function () { 8 | return this.salary; 9 | }, 10 | setSalary: function (salary) { 11 | this.salary = salary; 12 | }, 13 | accept: function (visitor) { 14 | visitor.visit(this); 15 | } 16 | } 17 | 18 | function Visitor() { } 19 | 20 | Visitor.prototype = { 21 | visit: function (employee) { 22 | employee.setSalary(employee.getSalary() * 2); 23 | } 24 | } 25 | 26 | const employee = new Employee('bruce', 1000); 27 | const visitor = new Visitor(); 28 | employee.accept(visitor); 29 | 30 | console.log(employee.getSalary()); 31 | 32 | 33 | -------------------------------------------------------------------------------- /Range.js: -------------------------------------------------------------------------------- 1 | function Range(start, end) { 2 | return { 3 | [Symbol.iterator]: function () { 4 | return { 5 | next() { 6 | if (start < end) { 7 | return { value: start++, done: false }; 8 | } 9 | return { done: true, value: end }; 10 | } 11 | } 12 | } 13 | } 14 | } 15 | 16 | // function Range(start, end) { 17 | // return { 18 | // [Symbol.iterator]() { // #A 19 | // return this; 20 | // }, 21 | // next() { 22 | // if (start < end) { 23 | // return { value: start++, done: false }; // #B 24 | // } 25 | // return { done: true, value: end }; // #B 26 | // } 27 | // } 28 | // } 29 | 30 | const range = Range(1, 5); 31 | console.log(range.next()); 32 | 33 | // for (num of Range(1, 5)) { 34 | // console.log(num); 35 | // } -------------------------------------------------------------------------------- /observer.js: -------------------------------------------------------------------------------- 1 | // 被观察者 2 | function Subject() { 3 | this.observers = []; 4 | } 5 | 6 | Subject.prototype = { 7 | // 订阅 8 | subscribe: function (observer) { 9 | this.observers.push(observer); 10 | }, 11 | // 取消订阅 12 | unsubscribe: function (observerToRemove) { 13 | this.observers = this.observers.filter(observer => { 14 | return observer !== observerToRemove; 15 | }) 16 | }, 17 | // 事件触发 18 | fire: function () { 19 | this.observers.forEach(observer => { 20 | observer.call(); 21 | }); 22 | } 23 | } 24 | 25 | const subject = new Subject(); 26 | 27 | function observer1() { 28 | console.log('Observer 1 Firing!'); 29 | } 30 | 31 | 32 | function observer2() { 33 | console.log('Observer 2 Firing!'); 34 | } 35 | 36 | subject.subscribe(observer1); 37 | subject.subscribe(observer2); 38 | // subject.fire(); 39 | 40 | subject.unsubscribe(observer2); 41 | subject.fire(); -------------------------------------------------------------------------------- /mediator.js: -------------------------------------------------------------------------------- 1 | function Member(name) { 2 | this.name = name; 3 | this.chatroom = null; 4 | } 5 | 6 | Member.prototype = { 7 | send: function (message, toMember) { 8 | this.chatroom.send(message, this, toMember); 9 | }, 10 | receive: function (message, fromMember) { 11 | console.log(`${fromMember.name} to ${this.name}: ${message}`); 12 | } 13 | } 14 | 15 | function Chatroom() { 16 | this.members = {}; 17 | } 18 | 19 | Chatroom.prototype = { 20 | addMember: function (member) { 21 | this.members[member.name] = member; 22 | member.chatroom = this; 23 | }, 24 | send: function (message, fromMember, toMember) { 25 | toMember.receive(message, fromMember); 26 | } 27 | } 28 | 29 | const chatroom = new Chatroom(); 30 | const bruce = new Member('bruce'); 31 | const frank = new Member('frank'); 32 | const alice = new Member('alice'); 33 | 34 | chatroom.addMember(bruce); 35 | chatroom.addMember(frank); 36 | chatroom.addMember(alice); 37 | 38 | bruce.send('Hey frank', frank); -------------------------------------------------------------------------------- /factory.js: -------------------------------------------------------------------------------- 1 | // 汽车构造函数 2 | function SuzukiCar(color) { 3 | this.color = color; 4 | this.brand = 'Suzuki'; 5 | } 6 | 7 | // 汽车构造函数 8 | function HondaCar(color) { 9 | this.color = color; 10 | this.brand = 'Honda'; 11 | } 12 | 13 | // 汽车构造函数 14 | function BMWCar(color) { 15 | this.color = color; 16 | this.brand = 'BMW'; 17 | } 18 | 19 | // 汽车品牌枚举 20 | const BRANDS = { 21 | suzuki: 1, 22 | honda: 2, 23 | bmw: 3 24 | } 25 | 26 | /** 27 | * 汽车工厂 28 | */ 29 | function CarFactory() { 30 | this.create = function (brand, color) { 31 | switch (brand) { 32 | case BRANDS.suzuki: 33 | return new SuzukiCar(color); 34 | case BRANDS.honda: 35 | return new HondaCar(color); 36 | case BRANDS.bmw: 37 | return new BMWCar(color); 38 | default: 39 | break; 40 | } 41 | } 42 | } 43 | 44 | const carFactory = new CarFactory(); 45 | const cars = []; 46 | 47 | cars.push(carFactory.create(BRANDS.suzuki, 'brown')); 48 | cars.push(carFactory.create(BRANDS.honda, 'grey')); 49 | cars.push(carFactory.create(BRANDS.bmw, 'red')); 50 | 51 | function say() { 52 | console.log(`Hi, I am a ${this.color} ${this.brand} car`); 53 | } 54 | 55 | for (const car of cars) { 56 | say.call(car); 57 | } -------------------------------------------------------------------------------- /momento.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Editor class 3 | */ 4 | class Editor { 5 | #content; 6 | #history = new History(); 7 | 8 | get content() { 9 | return this.#content; 10 | } 11 | 12 | set content(content) { 13 | this.#content = content; 14 | this.#history.push(this.createState()); 15 | } 16 | 17 | createState() { 18 | return new EditorState(this.#content); 19 | } 20 | 21 | restore() { 22 | const prevContent = this.#history.pop().content; 23 | this.#content = prevContent; 24 | } 25 | } 26 | 27 | /** 28 | * Editor state class 29 | */ 30 | class EditorState { 31 | #content; 32 | 33 | constructor(content) { 34 | this.#content = content; 35 | } 36 | 37 | get content() { 38 | return this.#content; 39 | } 40 | } 41 | 42 | /** 43 | * History class 44 | */ 45 | class History { 46 | #states = []; 47 | 48 | push(state) { 49 | this.#states.push(state); 50 | } 51 | 52 | pop() { 53 | return this.#states.pop(); 54 | } 55 | } 56 | 57 | const editor = new Editor(); 58 | 59 | editor.content = 'hello'; 60 | editor.content = 'world'; 61 | editor.content = 'i am'; 62 | editor.content = 'bruce'; 63 | 64 | editor.restore(); 65 | console.log(editor.content); 66 | editor.restore(); 67 | console.log(editor.content); 68 | editor.restore(); 69 | console.log(editor.content); 70 | editor.restore(); 71 | console.log(editor.content); 72 | -------------------------------------------------------------------------------- /proxy.js: -------------------------------------------------------------------------------- 1 | function StockPriceAPI() { 2 | this.getValue = function (stock, callback) { 3 | console.log('Calling external API ... '); 4 | setTimeout(() => { 5 | switch (stock) { 6 | case 'GOOGL': 7 | callback('$1265.23'); 8 | break; 9 | case 'AAPL': 10 | callback('$287.05'); 11 | break; 12 | case 'MSFT': 13 | callback('$173.70'); 14 | break; 15 | default: 16 | callback(''); 17 | } 18 | }, 2000); 19 | } 20 | } 21 | 22 | function StockPriceAPIProxy() { 23 | // 缓存对象 24 | this.cache = {}; 25 | // 真实API对象 26 | this.realAPI = new StockPriceAPI(); 27 | // Subject Interface实现 28 | this.getValue = function (stock, callback) { 29 | const cachedPrice = this.cache[stock]; 30 | if (cachedPrice) { 31 | console.log('Got price from cache'); 32 | callback(cachedPrice); 33 | } else { 34 | this.realAPI.getValue(stock, (price) => { 35 | this.cache[stock] = price; 36 | callback(price); 37 | }); 38 | } 39 | } 40 | } 41 | 42 | const api = new StockPriceAPIProxy(); 43 | api.getValue('GOOGL', (price) => { console.log(price) }); 44 | api.getValue('AAPL', (price) => { console.log(price) }); 45 | api.getValue('MSFT', (price) => { console.log(price) }); 46 | 47 | setTimeout(() => { 48 | api.getValue('GOOGL', (price) => { console.log(price) }); 49 | api.getValue('AAPL', (price) => { console.log(price) }); 50 | api.getValue('MSFT', (price) => { console.log(price) }); 51 | }, 3000) -------------------------------------------------------------------------------- /strategy.js: -------------------------------------------------------------------------------- 1 | const app = {}; 2 | 3 | /** 4 | * 登录控制器 5 | */ 6 | function LoginController() { 7 | this.strategy = undefined; 8 | this.setStrategy = function (strategy) { 9 | this.strategy = strategy; 10 | this.login = this.strategy.login; 11 | } 12 | } 13 | 14 | /** 15 | * 用户名、密码登录策略 16 | */ 17 | function LocalStragegy() { 18 | this.login = ({ username, password }) => { 19 | console.log(username, password); 20 | // authenticating with username and password... 21 | } 22 | } 23 | 24 | /** 25 | * 手机号、验证码登录策略 26 | */ 27 | function PhoneStragety() { 28 | this.login = ({ phone, verifyCode }) => { 29 | console.log(phone, verifyCode); 30 | // authenticating with hone and verifyCode... 31 | } 32 | } 33 | 34 | /** 35 | * 第三方社交登录策略 36 | */ 37 | function SocialStragety() { 38 | this.login = ({ id, secret }) => { 39 | console.log(id, secret); 40 | // authenticating with id and secret... 41 | } 42 | } 43 | 44 | const loginController = new LoginController(); 45 | 46 | // 调用用户名、密码登录接口,使用LocalStrategy 47 | app.use('/login/local', function (req, res) { 48 | loginController.setStrategy(new LocalStragegy()); 49 | loginController.login(req.body); 50 | }); 51 | 52 | // 调用手机、验证码登录接口,使用PhoneStrategy 53 | app.use('/login/phone', function (req, res) { 54 | loginController.setStrategy(new PhoneStragety()); 55 | loginController.login(req.body); 56 | }); 57 | 58 | // 调用社交登录接口,使用SocialStrategy 59 | app.use('/login/social', function (req, res) { 60 | loginController.setStrategy(new SocialStragety()); 61 | loginController.login(req.body); 62 | }); 63 | 64 | // loginController.setStrategy(new LocalStragegy()); 65 | // loginController.login({ username: 'bruce', password: '123456' }); 66 | // loginController.setStrategy(new PhoneStragety()); 67 | // loginController.login({ phone: '13851731474', verifyCode: '123456' }); 68 | // loginController.setStrategy(new SocialStragety()); 69 | // loginController.login({ id: 'bruce', secret: 'sdof83w0rhosdifh' }); 70 | 71 | -------------------------------------------------------------------------------- /assets/visitor.svg: -------------------------------------------------------------------------------- 1 | Elementaccept(v: Visitor)Visitorvisit(e: ElementA)visit(e: ElementB)ElementAaccept(v: Visitor)ElementBaccept(v: Visitor)VisitorAvisit(e: ElementA)visit(e: ElementB) -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ![Banner](http://lc-3Cv4Lgro.cn-n1.lcfile.com/c1af7a4c1b765d6fb777/banner.png) 2 | 3 | # 什么是设计模式? 4 | 5 | 设计模式是对软件设计开发过程中反复出现的某类问题的通用解决方案。设计模式更多的是指导思想和方法论,而不是现成的代码,当然每种设计模式都有每种语言中的具体实现方式。学习设计模式更多的是理解各种模式的内在思想和解决的问题,毕竟这是前人无数经验总结成的最佳实践,而代码实现则是对加深理解的辅助。 6 | 7 | # 设计模式的类型 8 | 9 | 设计模式可以分为三大类: 10 | 11 | 1. 结构型模式(Structural Patterns):通过识别系统中组件间的简单关系来简化系统的设计。 12 | 13 | 1. 创建型模式(Creational Patterns):处理对象的创建,根据实际情况使用合适的方式创建对象。常规的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。 14 | 15 | 1. 行为型模式(Behavioral Patterns):用于识别对象之间常见的交互模式并加以实现,如此,增加了这些交互的灵活性。 16 | 17 | 以上定义非常的抽象和晦涩,对于我们初学者并没有太多帮助,要了解这些设计模式真正的作用和价值还是需要通过实践去加以理解。这三大类设计模式又可以分成更多的小类,如下图: 18 | 19 | ![design patterns](http://lc-3Cv4Lgro.cn-n1.lcfile.com/960df36ee5a693833541/patterns.svg) 20 | 21 | 下面我们选择一些在前端开发过程中常见的模式进行一一讲解。 22 | 23 | # 一. 结构型模式(Structural Patterns) 24 | 25 | ## 1. 外观模式(Facade Pattern) 26 | 27 | ![facade](http://lc-3Cv4Lgro.cn-n1.lcfile.com/23064fc82c0d5b7b8d2d/facade.png) 28 | 29 | 外观模式是最常见的设计模式之一,它为子系统中的一组接口提供一个统一的高层接口,使子系统更容易使用。简而言之外观设计模式就是把多个子系统中复杂逻辑进行抽象,从而提供一个更统一、更简洁、更易用的API。很多我们常用的框架和库基本都遵循了外观设计模式,比如JQuery就把复杂的原生DOM操作进行了抽象和封装,并消除了浏览器之间的兼容问题,从而提供了一个更高级更易用的版本。其实在平时工作中我们也会经常用到外观模式进行开发,只是我们不自知而已。 30 | 31 | 比如,我们可以应用外观模式封装一个统一的DOM元素事件绑定/取消方法,用于兼容不同版本的浏览器和更方便的调用: 32 | 33 | ``` 34 | // 绑定事件 35 | function addEvent(element, event, handler) { 36 | if (element.addEventListener) { 37 | element.addEventListener(event, handler, false); 38 | } else if (element.attachEvent) { 39 | element.attachEvent('on' + event, handler); 40 | } else { 41 | element['on' + event] = fn; 42 | } 43 | } 44 | 45 | // 取消绑定 46 | function removeEvent(element, event, handler) { 47 | if (element.removeEventListener) { 48 | element.removeEventListener(event, handler, false); 49 | } else if (element.detachEvent) { 50 | element.detachEvent('on' + event, handler); 51 | } else { 52 | element['on' + event] = null; 53 | } 54 | } 55 | ``` 56 | 57 | ## 2. 代理模式(Proxy Pattern) 58 | 59 | ![proxy](http://lc-3Cv4Lgro.cn-n1.lcfile.com/5529c921e862b72a3746/proxy.png) 60 | 61 | 首先,一切皆可代理,不管是在实现世界还是计算机世界。现实世界中买房有中介、打官司有律师、投资有经纪人,他们都是代理,由他们帮你处理由于你缺少时间或者专业技能而无法完成的事务。类比到计算机领域,代理也是一样的作用,当访问一个对象本身的代价太高(比如太占内存、初始化时间太长等)或者需要增加额外的逻辑又不修改对象本身时便可以使用代理。ES6中也增加了 [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) 的功能。 62 | 63 | 归纳一下,代理模式可以解决以下的问题: 64 | 65 | 1. 增加对一个对象的访问控制 66 | 67 | 1. 当访问一个对象的过程中需要增加额外的逻辑 68 | 69 | 要实现代理模式需要三部分: 70 | 71 | 1. `Real Subject`:真实对象 72 | 73 | 1. `Proxy`:代理对象 74 | 75 | 1. `Subject`接口:Real Subject 和 Proxy都需要实现的接口,这样Proxy才能被当成Real Subject的“替身”使用 76 | 77 | 比如有一个股票价格查询接口,调用这个接口需要比较久的时间(用 `setTimeout` 模拟2s的调用时间): 78 | 79 | **StockPriceAPI:** 80 | 81 | ``` 82 | function StockPriceAPI() { 83 | // Subject Interface实现 84 | this.getValue = function (stock, callback) { 85 | console.log('Calling external API ... '); 86 | setTimeout(() => { 87 | switch (stock) { 88 | case 'GOOGL': 89 | callback('$1265.23'); 90 | break; 91 | case 'AAPL': 92 | callback('$287.05'); 93 | break; 94 | case 'MSFT': 95 | callback('$173.70'); 96 | break; 97 | default: 98 | callback(''); 99 | } 100 | }, 2000); 101 | } 102 | } 103 | ``` 104 | 105 | 我们不希望每次都去请求远程接口,而是增加缓存机制,当有缓存的时候就直接从缓存中获取,否则再去请求远程接口。我们可以通过一个proxy来实现: 106 | 107 | **StockPriceAPIProxy:** 108 | 109 | ``` 110 | function StockPriceAPIProxy() { 111 | // 缓存对象 112 | this.cache = {}; 113 | // 真实API对象 114 | this.realAPI = new StockPriceAPI(); 115 | // Subject Interface实现 116 | this.getValue = function (stock, callback) { 117 | const cachedPrice = this.cache[stock]; 118 | if (cachedPrice) { 119 | console.log('Got price from cache'); 120 | callback(cachedPrice); 121 | } else { 122 | this.realAPI.getValue(stock, (price) => { 123 | this.cache[stock] = price; 124 | callback(price); 125 | }); 126 | } 127 | } 128 | } 129 | ``` 130 | 131 | 注意,Proxy需要和真实对象一样实现 `getValue()` 方法,`getValue()`就属于 **Subject 接口**。 132 | 133 | 测试一下: 134 | 135 | ``` 136 | const api = new StockPriceAPIProxy(); 137 | api.getValue('GOOGL', (price) => { console.log(price) }); 138 | api.getValue('AAPL', (price) => { console.log(price) }); 139 | api.getValue('MSFT', (price) => { console.log(price) }); 140 | 141 | setTimeout(() => { 142 | api.getValue('GOOGL', (price) => { console.log(price) }); 143 | api.getValue('AAPL', (price) => { console.log(price) }); 144 | api.getValue('MSFT', (price) => { console.log(price) }); 145 | }, 3000) 146 | ``` 147 | 148 | **输出:** 149 | 150 | ``` 151 | Calling external API ... 152 | Calling external API ... 153 | Calling external API ... 154 | $1265.23 155 | $287.05 156 | $173.70 157 | Got price from cache 158 | $1265.23 159 | Got price from cache 160 | $287.05 161 | Got price from cache 162 | $173.70 163 | ``` 164 | 165 | 166 | # 二. 创建型模式(Creational Patterns) 167 | 168 | ## 1. 工厂模式(Factory Pattern) 169 | 170 | ![factory](http://lc-3Cv4Lgro.cn-n1.lcfile.com/3af93a26cdc73dd6b492/factory.png) 171 | 172 | 现实生活中的工厂按照既定程序制造产品,随着生产原料和流程不同生产出来的产品也会有区别。应用到软件工程的领域,工厂可以看成是一个制造其他对象的对象,制造出的对象也会随着传入工厂对象参数的不同而有所区别。 173 | 174 | 什么场景适合应用工厂模式而不是直接 `new` 一个对象呢?当构造函数过多不方便管理,且需要创建的对象之间存在某些关联(有同一个父类、实现同一个接口等)时,不妨使用工厂模式。工厂模式提供一种集中化、统一化的方式,避免了分散创建对象导致的代码重复、灵活性差的问题。 175 | 176 | 以上图为例,我们构造一个简单的汽车工厂来生产汽车: 177 | 178 | ``` 179 | // 汽车构造函数 180 | function SuzukiCar(color) { 181 | this.color = color; 182 | this.brand = 'Suzuki'; 183 | } 184 | 185 | // 汽车构造函数 186 | function HondaCar(color) { 187 | this.color = color; 188 | this.brand = 'Honda'; 189 | } 190 | 191 | // 汽车构造函数 192 | function BMWCar(color) { 193 | this.color = color; 194 | this.brand = 'BMW'; 195 | } 196 | 197 | // 汽车品牌枚举 198 | const BRANDS = { 199 | suzuki: 1, 200 | honda: 2, 201 | bmw: 3 202 | } 203 | 204 | /** 205 | * 汽车工厂 206 | */ 207 | function CarFactory() { 208 | this.create = function (brand, color) { 209 | switch (brand) { 210 | case BRANDS.suzuki: 211 | return new SuzukiCar(color); 212 | case BRANDS.honda: 213 | return new HondaCar(color); 214 | case BRANDS.bmw: 215 | return new BMWCar(color); 216 | default: 217 | break; 218 | } 219 | } 220 | } 221 | ``` 222 | 223 | **测试一下:** 224 | 225 | ``` 226 | const carFactory = new CarFactory(); 227 | const cars = []; 228 | 229 | cars.push(carFactory.create(BRANDS.suzuki, 'brown')); 230 | cars.push(carFactory.create(BRANDS.honda, 'grey')); 231 | cars.push(carFactory.create(BRANDS.bmw, 'red')); 232 | 233 | function say() { 234 | console.log(`Hi, I am a ${this.color} ${this.brand} car`); 235 | } 236 | 237 | for (const car of cars) { 238 | say.call(car); 239 | } 240 | ``` 241 | 242 | **输出:** 243 | 244 | ``` 245 | Hi, I am a brown Suzuki car 246 | Hi, I am a grey Honda car 247 | Hi, I am a red BMW car 248 | ``` 249 | 250 | 使用工厂模式之后,不再需要重复引入一个个构造函数,只需要引入工厂对象就可以方便的创建各类对象。 251 | 252 | ## 2. 单例模式(Singleton Pattern) 253 | 254 | ![singleton](http://lc-3Cv4Lgro.cn-n1.lcfile.com/7c16c62186e7d711218d/singleton.png) 255 | 256 | 顾名思义,单例模式中Class的实例个数最多为1。当需要一个对象去贯穿整个系统执行某些任务时,单例模式就派上了用场。而除此之外的场景尽量避免单例模式的使用,因为单例模式会引入全局状态,而一个健康的系统应该避免引入过多的全局状态。 257 | 258 | 实现单例模式需要解决以下几个问题: 259 | 260 | 1. 如何确定Class只有一个实例? 261 | 262 | 1. 如何简便的访问Class的唯一实例? 263 | 264 | 1. Class如何控制实例化的过程? 265 | 266 | 1. 如何将Class的实例个数限制为1? 267 | 268 | 我们一般通过实现以下两点来解决上述问题: 269 | 270 | 1. 隐藏Class的构造函数,避免多次实例化 271 | 272 | 1. 通过暴露一个 `getInstance()` 方法来创建/获取唯一实例 273 | 274 | Javascript中单例模式可以通过以下方式实现: 275 | 276 | ``` 277 | // 单例构造器 278 | const FooServiceSingleton = (function () { 279 | // 隐藏的Class的构造函数 280 | function FooService() {} 281 | 282 | // 未初始化的单例对象 283 | let fooService; 284 | 285 | return { 286 | // 创建/获取单例对象的函数 287 | getInstance: function () { 288 | if (!fooService) { 289 | fooService = new FooService(); 290 | } 291 | return fooService; 292 | } 293 | } 294 | })(); 295 | ``` 296 | 297 | 实现的关键点有:1. 使用 [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)创建局部作用域并即时执行;2. `getInstance()` 为一个 [闭包](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) ,使用闭包保存局部作用域中的单例对象并返回。 298 | 299 | 我们可以验证下单例对象是否创建成功: 300 | 301 | ``` 302 | const fooService1 = FooServiceSingleton.getInstance(); 303 | const fooService2 = FooServiceSingleton.getInstance(); 304 | 305 | console.log(fooService1 === fooService2); // true 306 | ``` 307 | 308 | # 三. 行为型模式(Behavioral Patterns) 309 | 310 | ## 1. 策略模式(Strategy Pattern) 311 | 312 | ![strategy](http://lc-3Cv4Lgro.cn-n1.lcfile.com/8371529e9200dba8abc4/strategy.png) 313 | 314 | 策略模式简单描述就是:对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。最常见的使用策略模式的场景如登录鉴权,鉴权算法取决于用户的登录方式是手机、邮箱或者第三方的微信登录等等,而且登录方式也只有在运行时才能获取,获取到登录方式后再动态的配置鉴权策略。所有这些策略应该实现统一的接口,或者说有统一的行为模式。Node 生态里著名的鉴权库 [Passport.js](http://www.passportjs.org/) API的设计就应用了策略模式。 315 | 316 | 还是以登录鉴权的例子我们仿照 **passport.js** 的思路通过代码来理解策略模式: 317 | 318 | ``` 319 | /** 320 | * 登录控制器 321 | */ 322 | function LoginController() { 323 | this.strategy = undefined; 324 | this.setStrategy = function (strategy) { 325 | this.strategy = strategy; 326 | this.login = this.strategy.login; 327 | } 328 | } 329 | 330 | /** 331 | * 用户名、密码登录策略 332 | */ 333 | function LocalStragegy() { 334 | this.login = ({ username, password }) => { 335 | console.log(username, password); 336 | // authenticating with username and password... 337 | } 338 | } 339 | 340 | /** 341 | * 手机号、验证码登录策略 342 | */ 343 | function PhoneStragety() { 344 | this.login = ({ phone, verifyCode }) => { 345 | console.log(phone, verifyCode); 346 | // authenticating with hone and verifyCode... 347 | } 348 | } 349 | 350 | /** 351 | * 第三方社交登录策略 352 | */ 353 | function SocialStragety() { 354 | this.login = ({ id, secret }) => { 355 | console.log(id, secret); 356 | // authenticating with id and secret... 357 | } 358 | } 359 | 360 | const loginController = new LoginController(); 361 | 362 | // 调用用户名、密码登录接口,使用LocalStrategy 363 | app.use('/login/local', function (req, res) { 364 | loginController.setStrategy(new LocalStragegy()); 365 | loginController.login(req.body); 366 | }); 367 | 368 | // 调用手机、验证码登录接口,使用PhoneStrategy 369 | app.use('/login/phone', function (req, res) { 370 | loginController.setStrategy(new PhoneStragety()); 371 | loginController.login(req.body); 372 | }); 373 | 374 | // 调用社交登录接口,使用SocialStrategy 375 | app.use('/login/social', function (req, res) { 376 | loginController.setStrategy(new SocialStragety()); 377 | loginController.login(req.body); 378 | }); 379 | ``` 380 | 381 | 从以上示例可以得出使用策略模式有以下优势: 382 | 383 | 1. 方便在运行时切换算法和策略 384 | 385 | 1. 代码更简洁,避免使用大量的条件判断 386 | 387 | 1. 关注分离,每个strategy类控制自己的算法逻辑,strategy和其使用者之间也相互独立 388 | 389 | ## 2. 迭代器模式(Iterator Pattern) 390 | 391 | ![iterator](http://lc-3Cv4Lgro.cn-n1.lcfile.com/aeaeff96a83849a91731/Iterator.png) 392 | 393 | ES6中的迭代器 [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) 相信大家都不陌生,迭代器用于遍历容器(集合)并访问容器中的元素,而且无论容器的数据结构是什么(Array、Set、Map等),迭代器的接口都应该是一样的,都需要遵循 [迭代器协议](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol)。 394 | 395 | 迭代器模式解决了以下问题: 396 | 397 | 1. 提供一致的遍历各种数据结构的方式,而不用了解数据的内部结构 398 | 399 | 1. 提供遍历容器(集合)的能力而无需改变容器的接口 400 | 401 | 一个迭代器通常需要实现以下接口: 402 | 403 | * `hasNext()`:判断迭代是否结束,返回Boolean 404 | 405 | * `next()`:查找并返回下一个元素 406 | 407 | 为Javascript的数组实现一个迭代器可以这么写: 408 | 409 | ``` 410 | const item = [1, 'red', false, 3.14]; 411 | 412 | function Iterator(items) { 413 | this.items = items; 414 | this.index = 0; 415 | } 416 | 417 | Iterator.prototype = { 418 | hasNext: function () { 419 | return this.index < this.items.length; 420 | }, 421 | next: function () { 422 | return this.items[this.index++]; 423 | } 424 | } 425 | ``` 426 | 427 | 验证一下迭代器是否工作: 428 | 429 | ``` 430 | const iterator = new Iterator(item); 431 | 432 | while(iterator.hasNext()){ 433 | console.log(iterator.next()); 434 | } 435 | ``` 436 | **输出:** 437 | 438 | ``` 439 | 1, red, false, 3.14 440 | ``` 441 | 442 | ES6提供了更简单的迭代循环语法 `for...of`,使用该语法的前提是操作对象需要实现 [可迭代协议(The iterable protocol)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols),简单说就是该对象有个Key为 `Symbol.iterator` 的方法,该方法返回一个iterator对象。 443 | 444 | 比如我们实现一个 `Range` 类用于在某个数字区间进行迭代: 445 | 446 | ``` 447 | function Range(start, end) { 448 | return { 449 | [Symbol.iterator]: function () { 450 | return { 451 | next() { 452 | if (start < end) { 453 | return { value: start++, done: false }; 454 | } 455 | return { done: true, value: end }; 456 | } 457 | } 458 | } 459 | } 460 | } 461 | ``` 462 | 463 | **验证一下:** 464 | 465 | ``` 466 | for (num of Range(1, 5)) { 467 | console.log(num); 468 | } 469 | ``` 470 | 471 | **输出:** 472 | ``` 473 | 1, 2, 3, 4 474 | ``` 475 | 476 | ## 3. 观察者模式(Observer Pattern) 477 | 478 | ![observer](http://lc-3Cv4Lgro.cn-n1.lcfile.com/252c467e10809ca02945/observer.png) 479 | 480 | 观察者模式又称发布订阅模式(Publish/Subscribe Pattern),是我们经常接触到的设计模式,日常生活中的应用也比比皆是,比如你订阅了某个博主的频道,当有内容更新时会收到推送;又比如JavaScript中的事件订阅响应机制。观察者模式的思想用一句话描述就是:**被观察对象(subject)维护一组观察者(observer),当被观察对象状态改变时,通过调用观察者的某个方法将这些变化通知到观察者**。 481 | 482 | 比如给DOM元素绑定事件的 `addEventListener()` 方法: 483 | 484 | ``` 485 | target.addEventListener(type, listener [, options]); 486 | ``` 487 | 488 | Target就是被观察对象Subject,listener就是观察者Observer。 489 | 490 | 观察者模式中Subject对象一般需要实现以下API: 491 | 492 | * `subscribe()`: 接收一个观察者observer对象,使其订阅自己 493 | 494 | * `unsubscribe()`: 接收一个观察者observer对象,使其取消订阅自己 495 | 496 | * `fire()`: 触发事件,通知到所有观察者 497 | 498 | 用JavaScript手动实现观察者模式: 499 | 500 | ``` 501 | // 被观察者 502 | function Subject() { 503 | this.observers = []; 504 | } 505 | 506 | Subject.prototype = { 507 | // 订阅 508 | subscribe: function (observer) { 509 | this.observers.push(observer); 510 | }, 511 | // 取消订阅 512 | unsubscribe: function (observerToRemove) { 513 | this.observers = this.observers.filter(observer => { 514 | return observer !== observerToRemove; 515 | }) 516 | }, 517 | // 事件触发 518 | fire: function () { 519 | this.observers.forEach(observer => { 520 | observer.call(); 521 | }); 522 | } 523 | } 524 | ``` 525 | 526 | 验证一下订阅是否成功: 527 | 528 | ``` 529 | const subject = new Subject(); 530 | 531 | function observer1() { 532 | console.log('Observer 1 Firing!'); 533 | } 534 | 535 | 536 | function observer2() { 537 | console.log('Observer 2 Firing!'); 538 | } 539 | 540 | subject.subscribe(observer1); 541 | subject.subscribe(observer2); 542 | subject.fire(); 543 | ``` 544 | 545 | **输出:** 546 | 547 | ``` 548 | Observer 1 Firing! 549 | Observer 2 Firing! 550 | ``` 551 | 552 | 验证一下取消订阅是否成功: 553 | 554 | ``` 555 | subject.unsubscribe(observer2); 556 | subject.fire(); 557 | ``` 558 | 559 | **输出:** 560 | 561 | ``` 562 | Observer 1 Firing! 563 | ``` 564 | 565 | ## 4. 中介者模式(Mediator Pattern) 566 | 567 | ![mediator](http://lc-3Cv4Lgro.cn-n1.lcfile.com/f5e2d4040c795599060d/mediator.png) 568 | 569 | 在中介者模式中,中介者(Mediator)包装了一系列对象相互作用的方式,使得这些对象不必直接相互作用,而是由中介者协调它们之间的交互,从而使它们可以松散偶合。当某些对象之间的作用发生改变时,不会立即影响其他的一些对象之间的作用,保证这些作用可以彼此独立的变化。 570 | 571 | 中介者模式和观察者模式有一定的相似性,都是一对多的关系,也都是集中式通信,不同的是中介者模式是处理同级对象之间的交互,而观察者模式是处理Observer和Subject之间的交互。中介者模式有些像婚恋中介,相亲对象刚开始并不能直接交流,而是要通过中介去筛选匹配再决定谁和谁见面。中介者模式比较常见的应用比如聊天室,聊天室里面的人之间并不能直接对话,而是通过聊天室这一媒介进行转发。一个简易的聊天室模型可以实现如下: 572 | 573 | **聊天室成员类:** 574 | 575 | ``` 576 | function Member(name) { 577 | this.name = name; 578 | this.chatroom = null; 579 | } 580 | 581 | Member.prototype = { 582 | // 发送消息 583 | send: function (message, toMember) { 584 | this.chatroom.send(message, this, toMember); 585 | }, 586 | // 接收消息 587 | receive: function (message, fromMember) { 588 | console.log(`${fromMember.name} to ${this.name}: ${message}`); 589 | } 590 | } 591 | ``` 592 | 593 | **聊天室类:** 594 | 595 | ``` 596 | function Chatroom() { 597 | this.members = {}; 598 | } 599 | 600 | Chatroom.prototype = { 601 | // 增加成员 602 | addMember: function (member) { 603 | this.members[member.name] = member; 604 | member.chatroom = this; 605 | }, 606 | // 发送消息 607 | send: function (message, fromMember, toMember) { 608 | toMember.receive(message, fromMember); 609 | } 610 | } 611 | ``` 612 | 613 | **测试一下:** 614 | 615 | ``` 616 | const chatroom = new Chatroom(); 617 | const bruce = new Member('bruce'); 618 | const frank = new Member('frank'); 619 | 620 | chatroom.addMember(bruce); 621 | chatroom.addMember(frank); 622 | 623 | bruce.send('Hey frank', frank); 624 | ``` 625 | 626 | **输出:** 627 | 628 | ``` 629 | bruce to frank: hello frank 630 | ``` 631 | 632 | 这只是一个最简单的聊天室模型,真正的聊天室还可以加入更多的功能,比如敏感信息拦截、一对多聊天、广播等。得益于中介者模式,Member不需要处理和聊天相关的复杂逻辑,而是全部交给Chatroom,有效的实现了关注分离。 633 | 634 | 635 | ## 5. 访问者模式(Visitor Pattern) 636 | 637 | ![visitor](http://lc-3Cv4Lgro.cn-n1.lcfile.com/e46eca323512078a4db3/visitor.svg) 638 | 639 | 访问者模式是一种将算法与对象结构分离的设计模式,通俗点讲就是:访问者模式让我们能够在不改变一个对象结构的前提下能够给该对象增加新的逻辑,新增的逻辑保存在一个独立的访问者对象中。访问者模式常用于拓展一些第三方的库和工具。 640 | 641 | 访问者模式的实现有以下几个要素: 642 | 643 | 1. `Visitor Object`:访问者对象,拥有一个 `visit()` 方法 644 | 645 | 1. `Receiving Object`:接收对象,拥有一个 `accept()` 方法 646 | 647 | 1. `visit(receivingObj)`:用于Visitor接收一个Receiving Object 648 | 649 | 1. `accept(visitor)`:用于Receving Object接收一个Visitor,并通过调用Visitor的 `visit()` 为其提供获取Receiving Object数据的能力 650 | 651 | 简单的代码实现如下: 652 | 653 | **Receiving Object:** 654 | 655 | ``` 656 | function Employee(name, salary) { 657 | this.name = name; 658 | this.salary = salary; 659 | } 660 | 661 | Employee.prototype = { 662 | getSalary: function () { 663 | return this.salary; 664 | }, 665 | setSalary: function (salary) { 666 | this.salary = salary; 667 | }, 668 | accept: function (visitor) { 669 | visitor.visit(this); 670 | } 671 | } 672 | ``` 673 | 674 | **Visitor Object:** 675 | 676 | ``` 677 | function Visitor() { } 678 | 679 | Visitor.prototype = { 680 | visit: function (employee) { 681 | employee.setSalary(employee.getSalary() * 2); 682 | } 683 | } 684 | ``` 685 | 686 | **验证一下:** 687 | 688 | ``` 689 | const employee = new Employee('bruce', 1000); 690 | const visitor = new Visitor(); 691 | employee.accept(visitor); 692 | 693 | console.log(employee.getSalary()); 694 | ``` 695 | 696 | **输出:** 697 | ``` 698 | 2000 699 | ``` 700 | 701 | 本文仅仅初步探讨了部分设计模式在前端领域的应用或者实现,旨在消除大部分同学心中对设计模式的陌生感和畏惧感。现有的设计模式就有大约50中,常见的也有20种左右,所以设计模式是一门宏大而深奥的学问需要我们不断的去学习和在实践中总结。本文所涉及到的9种只占了一小部分,未涉及到的模式里面肯定也有对前端开发有价值的,希望以后有机会能一一补上。谢谢阅读🙏! 702 | 703 | 本文源码请参考:https://github.com/MudOnTire/frontend-design-patterns --------------------------------------------------------------------------------