Js implements 23 design patterns

Recently, I have been learning 23 object-oriented design modes, which have been realized using Java and javascript. However, since I am in my junior year, I have not had formal major project experience, so I think it is difficult to fully control the learning process without certain project experience. Therefore, in the process of learning, I only roughly learned the characteristics of each design mode. I think we should find the scene to achieve in the process of learning, so that the learning effect is very good. The following is the code, of course, for reference only. Here’s the code:

Creation pattern

The singleton pattern

The three elements:

  • Same instance
  • Class creates its own instance object
  • You can output this instance to the entire system

Classification:

  • Hungry (creating instance objects when the class is loaded into the instance)
  • Lazy (creating instance objects when first used)

Code example: slob style

// Cell phones are used for making calls, playing games, watching movies, Var res = function () {throw new Error("Please use Phone.getInstance() to get the object."); }; var has = false; var phone = null; Object.defineProperty(res, 'getInstance', { value: function () { if (has) { return phone; } else { has = true; Phone = {call () {console.log(" call "); }, playGame () {console.log(" play the game "); }, watchMovie () {console.log(" watch movies "); } } return phone; } }, writable: false, configurable: false, enumerable: false }); return res; } ()); var p1 = Phone.getInstance(); var p2 = Phone.getInstance(); var p3 = Phone.getInstance(); p1.call(); p2.playGame(); p3.watchMovie(); console.log(p1 === p2 && p2 === p3);Copy the code

Code example: Hungry

Var Phone = (function () {var Phone = (function () {var Phone = (function ()) {var Phone = (function () { Var phone = {call () {console.log(" call "); var phone = {call () {console.log(" call "); }, playGame () {console.log(" play the game "); }, watchMovie () {console.log(" watch movies "); }}; var res = function () { throw new Error("Please use Phone.getInstance() to get the object."); }; Object.defineProperty(res, 'getInstance', { value: function () { return phone; }, writable: false, configurable: false, enumerable: false }); return res; } ()); var p1 = Phone.getInstance(); var p2 = Phone.getInstance(); var p3 = Phone.getInstance(); p1.call(); p2.playGame(); p3.watchMovie(); console.log(p1 === p2 && p2 === p3); Phone.getInstance = function () { console.log("I am Groot!" ); } var p4 = Phone.getInstance(); p4.call();Copy the code

Simple Factory model

Definition:

Defines a factory, which defines a method that returns an instance of a class based on the parameters passed in.

Code examples:

Const Vehicle = {run () {console.log(this.name + 'run... '); Function Car () {this.name = "Car "; } Car.prototype = Object.assign(Vehicle); Function Moto () {this.name = "Moto "; } Moto.prototype = Object.assign(Vehicle); Const Garage = {chooseVehicle (constructor) {return new constructor(); }}; Object.freeze(Garage); var car = Garage.chooseVehicle(Car); var moto = Garage.chooseVehicle(Moto); car.run(); moto.run();Copy the code

The factory method

Brief: Define a factory interface that has a method for creating product classes. Create one such class factory for each class.

Code examples:

Const Vehicle = {run () {console.log(this.name + 'run... '); Function Car () {this.name = "Car "; } Car.prototype = Object.assign(Vehicle); Function Moto () {this.name = "Moto "; } Moto.prototype = Object.assign(Vehicle); Function CarGarage () {this.createveHicle = function () {return new Car(); } Object.freeze(this); } function MotoGarage () {this.createvehicle = function () {return new Moto(); } Object.freeze(this); } var carGarage = new carGarage (); var motoGarage = new MotoGarage(); var car = carGarage.createVehicle(); var moto = motoGarage.createVehicle(); car.run(); moto.run();Copy the code

The abstract factory

Brief: In contrast to the factory method, an abstract factory can be described as a variety of products, each of which is implemented using the factory method.

Code examples:

// ak47 gun factory, Function Ak47GunCompany () {this.creategun = function () {console.log(" Ak47GunCompany...") {this.creategun = function () {console.log(" Ak47GunCompany... ); }} function BarrettGunCompany () {this.creategun = function () {console.log(" BarrettGunCompany...") {console.log(" console.log ") {console.log(" console.log "); ); }} // createBubble bullets factory // ak47 bullets factory, Function Ak47BubbleCompany () {this.createBubble = function () {console.log(" Bubblecompany ") {this.createBubble = function () {console.log(" Bubblecompany "... ); }} // Barrett Bullet Factory, Function BarrettBubbleCompany () {this.createBubble = function () {console.log(" Bubblecompany...") {this.createBubble = function () {console.log(" Bubblecompany... ); }} // Weapon factory, manufacture guns and bullets // createGun manufacture guns // createBubble manufacture bullets // AK47 weapon factory, Function ak47GunCompany () {var ak47GunCompany = new ak47GunCompany (); var ak47BubbleCompany = new Ak47BubbleCompany(); this.createGun = function () { ak47GunCompany.createGun(); } this.createBubble = function () { ak47BubbleCompany.createBubble(); }} function barrettGunCompany () {var barrettGunCompany = new barrettGunCompany (); var barrettBubbleCompany = new BarrettBubbleCompany(); this.createGun = function () { barrettGunCompany.createGun(); } this.createBubble = function () { barrettBubbleCompany.createBubble(); } } var ak47Company = new Ak47Company(); var barrettCompany = new BarrettCompany(); ak47Company.createGun(); ak47Company.createBubble(); barrettCompany.createGun(); barrettCompany.createBubble();Copy the code

Builder model

Brief: When constructing an instance, you need to perform multiple steps to generate the instance, and each step has multiple options to generate multiple instances.

Code examples:

// Apply to the multiple steps required to construct an instance object, Function WatermelonJuiceStep() {function WatermelonJuiceStep() {function WatermelonJuiceStep() This.stirfruit = function () {console.log("...") {this.stirfruit = function () {console.log("... ); }; This.addwater = function () {console.log(" addWater... ); }} function OrangeJuiceStep() {this.stirfruit = function () {console.log("... ); }; This.addwater = function () {console.log(" addWater... ); Function WatermelonJuiceMaker () {var maker = new WatermelonJuiceStep(); this.make = function () { maker.StirFruit(); maker.addWater(); } this.getJuice = function () { return maker; }} function OrangeJuiceMaker () {var maker = new OrangeJuiceStep(); this.make = function () { maker.StirFruit(); maker.addWater(); } this.getJuice = function () { return maker; }} function orangeJuiceMaker () {var orangeJuiceMaker = new orangeJuiceMaker (); var watermelonJuiceMaker = new WatermelonJuiceMaker(); this.makeOrangeJuice = function () { orangeJuiceMaker.make(); return orangeJuiceMaker.getJuice(); } this.makeWatermelonJuice = function () { watermelonJuiceMaker.make(); return watermelonJuiceMaker.getJuice(); Var juiceMaker = new juiceMaker (); var watermelonJuice = juiceMaker.makeWatermelonJuice(); var orangeJuice = juiceMaker.makeOrangeJuice();Copy the code

Structural mode

The proxy pattern

A proxy class contains a proxied class (HAS-A). Example of this code:

// Proxy mode // common inheritance of the same interface or abstract class, proxy class contains the promenade class (HAS-a) // scenario: */ function testSelf() {this.test = function() {console.log(); But I can't."); Function testOther(self) {this.test = function() {console.log(" take the test, I will.");}} / / function testOther(self) {this.test = function() {console.log(" take the test, I will. Var self = new testSelf(); var other = new testOther(self); other.test();Copy the code

Adapter mode

Example of code that takes two interfaces or classes that do not work together and makes them work together by creating a new class that inherits them:

// Adapter pattern // Take two interfaces or classes that don't work together and create a new class that inherits both, Function Mi8() {this.access = function () {function Mi8() {this.access = function () { Console. log(" Mi 8 provides square jack."); }} /** Headset */ headset () {this.insert = function () {console.log(" Headset comes with a round plug."); Function HeadsetAdapter() {this.access = function () {console.log(" HeadsetAdapter provides a circular socket."); } this.insert = function () {console.log(" Headphone adapter provides square plug."); Var mi8 = new mi8 (); var miHeadset = new MiHeadset(); var headsetAdapter = new HeadsetAdapter(); mi8.access(); headsetAdapter.insert(); headsetAdapter.access(); miHeadset.insert();Copy the code

The bridge model

Brief: Mainly two different classes have a variety of types, through has-A combination to carry out a variety of combinations of examples code:

// ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * ShoesBar * saleShoes() * */ function RunShoesBar() {this.saleshoes = function () {console.log(" sell shoes "); }} /** / function BasketballShoesBar() {this.saleshoes = function () {console.log(" sell BasketballShoesBar "); }} /** abstract class: shoesBar inherits shoesBar */ ** Brand shoe store inherits class: * */ function shoesBar (shoesBar) {var shoesBar = shoesBar; This.saleshoes = function () {console.log(" console.log "); shoesBar.saleShoes(); }} /** / function NickShoesBar(shoesBar) {var shoesBar = shoesBar; This.saleshoes = function () {console.log(" Nike: "); shoesBar.saleShoes(); Var runShoesBar = new runShoesBar (); Var liningRunShoesBar = new LiNingShoesBar(runShoesBar); liningRunShoesBar.saleShoes(); Var nickShoesBar = new nickShoesBar (runShoesBar); nickShoesBar.saleShoes();Copy the code

Portfolio model

Simple: two classes at different levels have very similar structures, so you can construct only one class to represent them

// Two classes at different levels have very similar structures, so you can construct only one class to represent these two classes // scenario: grandparent, father, son // interface: Const Person = {getName() {return this.name; }, setName(name) { this.name = name; }, display () {}} // Grandpa and dad are both fathers, both have sons, so... function Father(name) { this.setName(name); var sons = []; this.add = function (person) { sons.push(person); } this.display = function () {console.log(" father: "+ this.getName()); sons.forEach((son) => { son.display(); }); }} Father. Prototype = Person; Function Son(name) {this.setname (name); This.display = function () {console.log(" as son: "+ this.getName()); Prototype = Person; Var grandfather = new Father(" grandfather "); Var father1 = new Father(" Father "); Var father2 = new Father; Var son1 = new Son(" son1 "); Var son2 = new Son(" son2 "); grandfather.add(father1); grandfather.add(father2); father1.add(son1); father2.add(son2); grandfather.display();Copy the code

Decorative pattern

Examples of code for the decorator pattern, in which the base class and the decorator class share an interface or abstract class, decorator the base class by including the base class and adding decorator methods to the decorator class:

// Scene: LOL hero buff, normal hero, Lulu buff, Nunu buff /** Public interface: */ function NormalHero() {this.getbuff = function () {console.log(" initial Hero, no buff."); Function () {hero.getbuff = function() {hero.getbuff (); Console. log(" Add Lulu buff."); Function NuNuBuffHero(hero) {this.getbuff = function () {hero.getbuff (); Console. log(" Ganunu buff."); Var noBuffHero = new NormalHero(); var luluBuffHero = new LuLuBuffHero(noBuffHero); var nunuBuffHero = new NuNuBuffHero(luluBuffHero); nunuBuffHero.getBuff();Copy the code

The appearance model

Brief: Examples of code that manages internal classes through a unified management class while exposing interfaces to receive messages from external classes:

/** External mode * Manages internal classes through a unified management class, while exposing interfaces to receive messages from external classes */ / Scenario description: Demanders make requirements, developers develop, testers test. // Demanders don't need to tell developers to develop, testers to test. // Developers just need to tell the team leader the requirements. Function Developter() {this.develop = function(demand_name) {console.log(" demand_name: + demand_name); Function Tester() {this.test = function (demand_name) {console.log(" demand_name: "+ demand_name); Function Leader() {var developer = new Developter(); var tester = new Tester(); this.processDemand = function (demand_name) { developer.develop(demand_name); tester.test(demand_name); Function Demander() {var leader = new leader (); Demand_name = function (demand_name) {console.log(" demand_name: "+ demand_name); leader.processDemand(demand_name); Var demand_name = "Make a MOBA game."; var demander = new Demander(); demander.demand(demand_name);Copy the code

The flyweight pattern

Brief: For some objects used in the system can be shared, so each time you use it, check whether there is a direct use, no more to create, save memory space code example:

The flyweight pattern / * * * for some objects used in the system can be used to share, so every time use to judge whether you * first have used directly, not to create, save memory space * / / / scene: / / local tyrants to play the hero alliance, which want to use the skin, with which / / a skin used directly, not buy buy buy... /** HeroSkin class * name * show() */ function HeroSkin(name) {console.log(" player bought "+ name +" skin "); This.show = function () {console.log(" player used "+ name +" skin "); }} /** useSkin */ function Player() {var mySkins = {}; this.useSkin = function (skinName) { if (! (skinName in mySkins)) { mySkins[skinName] = new HeroSkin(skinName); } mySkins[skinName].show(); Var player = new player (); Player.useskin (" Izelir - Future Warrior "); Player. UseSkin (" Raven - Lightbringer "); Player. UseSkin (" Raven - Lightbringer ");Copy the code

Behavioral pattern

Template method

Brief: simply define what a subclass needs to do, and give it to the subclass to do the specific code example (Java, because JS has no abstract methods, and I think the template method is mainly a fixed flow, implementation to the subclass implementation)

package actionModel.templateModel; // Template method // Scene: Summoner selects hero, Skin and Summoner skill // Steps: Select Hero -> Select Skin -> Select Summoner skill 1 -> Select Summoner skill 2 // Character: Abstract class Player {private String name; public Player(String name) { this.name = name; } public abstract void chooseHero(); public abstract void chooseSkin(); public abstract void chooseSummonerSkillFirst(); public abstract void chooseSummonerSkillSecond(); Public void show() {// Display player info system.out.println (this.name + "select: "); // Show the selected hero chooseHero(); // Show the selected skin chooseSkin(); // Show the selected summoner skill one chooseSummonerSkillFirst(); / / display select summoner skill chooseSummonerSkillSecond (); }} class XiaoMing extends Player{public XiaoMing(){super(" XiaoMing "); } @override public void chooseHero() {system.out.println (" hero: Olaf "); } @override public void chooseSkin() {system.out.println (); } @override public void chooseSummonerSkillFirst() {system.out.println (); {} @ Override public void chooseSummonerSkillSecond () System. The out. Println (" summoner skills 2: flash "); }} class XiaoZhang extends Player {public XiaoZhang() {super(" XiaoZhang "); } @override public void chooseHero() {system.out.println (" hero "); } @override public void chooseSkin() {system.out.println (" skin: light "); } @override public void chooseSummonerSkillFirst() {system.out.println (); {} @ Override public void chooseSummonerSkillSecond () System. The out. Println (" summoner skills 2: flash "); }} public class Test {public static void main(String[] args) {// Test Player xiaoming = new xiaoming (); Player xiaozhang = new XiaoZhang(); xiaoming.show(); xiaozhang.show(); }}Copy the code

The mediator pattern

Brief: Simply put, data is passed through intermediaries, one party provides data, one party subscribes data code example:

// Broker mode // Simply put, data is passed through intermediaries // One party provides data, one party subscribes data // scenario: Use a third party to buy a second-hand phone // The buyer to order the phone, /** Buyer constructor ** @param phoneName required by Buyer */ function Buyer(phoneName) {this.getphonename = function() { return phoneName; } this.callSellerPhone = function(phone) {console.log(' contact seller: ${phone} buy ${phoneName} '); }} /** Seller constructor * @param phoneName Seller * @param phone Seller contact */ function Seller(phoneName, phoneName) phone) { this.getPhoneName = function() { return phoneName; } this.getPhone = function() { return phone; }}} /** / function {}}}}} /** / function {}} var sellerList = []; This. AddBuyer = function(buyer) {// If there is a suitable buyer, For (let I of sellerList) {if (i.getphonename () === buyer.getphonename ()) {buyer.callsellerphone (i.getphone ());  break; } } buyerList.push(buyer); } this.addSeller = function(seller) {// If there is a suitable buyer, notify the buyer directly. For (let I of buyerList) {if (i.getphonename () === buyer.getphonename ()) { i.callSellerPhone(seller.getPhone()); break; } } sellerList.push(seller); } } var intermediary = new Intermediary(); Var buyer1 = new Buyer(" buyer1 "); intermediary.addBuyer(buyer1); Var buyer2 = new Buyer(" buyer2 "); intermediary.addBuyer(buyer2); Var seller1 = new Seller(); var seller2 = new Seller(); intermediary.addSeller(seller1);Copy the code

Command mode

Summary: Using command mode, you can extend the scheduling center without modifying the scheduling center code. Example of this code:

// Command mode // The command mode can be used to expand the scheduling center without modifying the scheduling center code // scenario: Function ToyCar() {this.goon = function() {console.log(" ToyCar "); } this.stop = function() {console.log(" stop "); } this.speedup = function() {console.log(" speedUp "); }} /** CarCommand extends CarCommand @param Car instance */ function GoOnCommand(car) { this.execute = function() { car.goOn(); }} /** extends CarCommand * @param car extends CarCommand */ function StopCommand(car) {this.execute = function() { car.stop(); }} /** extends CarCommand * @param car */ function SpeedUpCommand(car) {this.execute = function() { car.speedUp(); Function CarControlHandle() {var carCommand = null; var carCommand = null; this.setCommand = function(newCarCommand) { carCommand = newCarCommand; } this.trigger = function() { carCommand.execute(); Var car = new ToyCar(); var controlHandle = new CarControlHandle(); var goOn = new GoOnCommand(car); controlHandle.setCommand(goOn); controlHandle.trigger(); var stop = new StopCommand(car); controlHandle.setCommand(stop); controlHandle.trigger(); var speedUp = new SpeedUpCommand(car); controlHandle.setCommand(speedUp); controlHandle.trigger();Copy the code

Chain of Responsibility model

Brief: the request is handed to a processing chain, which is processed by multiple processors. When a processor on the processing chain processes the request, the result of processing is returned. The advantage is that the internal code does not need to be modified when the processor is added or deleted

Code examples:

/ / chain of responsibility pattern / / the request to a processing chain, treatment with multiple processors on the chain, / / when a processor handles the request processing chain, processing the return / / advantage is when the add or remove the processor does not need to modify the internal code, you just need to add or delete / / in accordance with the open closed principle / / scene: DNF players brush to hit monsters, monsters have ordinary monsters, elite monsters, Boss /** monster abstract class * nextMonster nextMonster * setNextMonster sets nextMonster * battle() and player combat * battleSuccess() battle victory * battalFail() battle failure */ /** / function nextMonster () {var nextMonster = null; this.setNextMonster = function(Monster) { nextMonster = Monster; } this.battle = function(player) { var res = Math.round(Math.random() * 10) % 2 === 0; if (res) { this.battleSuccess(); nextMonster.battle(player); } else { this.battleFail(); }} this.battlesuccess = function() {console.log(" Beat the normal monster "); } this.battlefail = function() {console.log(" killed by ordinary monsters, please use the revive coin "); } /** / function CreamMonster() {var nextMonster = null; this.setNextMonster = function(Monster) { nextMonster = Monster; } this.battle = function(player) { var res = Math.round(Math.random() * 10) % 2 === 0; if (res) { this.battleSuccess(); nextMonster.battle(player); } else { this.battleFail(); }} this.battlesuccess = function() {console.log(" Beat the elitemonster "); } this.battlefail = function() {console.log(" killed by elite monster, please use revive coin "); } /** / function BossMonster() {var nextMonster = null; this.setNextMonster = function(Monster) { nextMonster = Monster; } this.battle = function(player) { var res = Math.round(Math.random() * 10) % 2 === 0; if (res) { this.battleSuccess(); } else { this.battleFail(); }} this.battlesuccess = function() {console.log(" beat the boss! ); } this.battlefail = function() {console.log(" killed by boss, please use revive coin "); Function Player() {} var Player = new Player(); var nomalMonster = new NomalMonster(); var creamMonster = new CreamMonster(); nomalMonster.setNextMonster(creamMonster); var bossMonster = new BossMonster(); creamMonster.setNextMonster(bossMonster); nomalMonster.battle(player);Copy the code

The strategy pattern

Brief: Define a set of algorithms, encapsulate each algorithm, and make them interchangeable

Code examples:

// Strategy pattern // Define a set of algorithms, encapsulate each algorithm, and make them interchangeable // scenario: five people rent a house, either looking for five rooms and one hall, or three rooms and one hall + two rooms and one hall // role: SayMethod () {this.saymethod = function() {this.saymethod = function() {this.saymethod = function() { Console. log(" Find a room with five rooms."); SayMethod () {this.saymethod = function() {this.saymethod = function() {this.saymethod = function() { Console. log(" Find one with three bedrooms and one with two bedrooms "); }} function findHouse(method) {this.findhouse = function() {this.findhouse = function() {this.findhouse = function() { method.sayMethod(); } this.setMethod = function(newMethod) { method = newMethod; Var method = new Method1(); var people = new findHousePeople(method); people.findHouse(); method = new Method2(); people.setMethod(method); people.findHouse();Copy the code

Iterator pattern

Brief: Given a traversal rule, regardless of its data structure implementation

Code examples:

// Iterator pattern // Given a traversal rule, regardless of its data structure implementation // scenario: /** Student constructor ** / function Student(name, phone, expressId) {this.getName = function() {return name; } this.getPhone = function() { return phone; } this.getExpressId = function() { return expressId; } /* / function ExpressStation() {var index = -1; var students = []; var iterator = null; iterator = { hasNext() { return index < students.length - 1; }, next() { index ++; return students[index]; } } this.getIterator = function() { return iterator; } this.addStudent = function(student) { students.push(student); }} var s1 = new Student(" Student ", "15684175538", "5-68 "); Var s2 = new Student(" Student ", "15806378470", "5-98-6"); var expressStation = new ExpressStation(); expressStation.addStudent(s1); expressStation.addStudent(s2); var iterator = expressStation.getIterator(); while (iterator.hasNext()) { var student = iterator.next(); Console. log(' Courier: "next" '); Console. log(' student: "${student.getExpressid ()}" '); Console. log(' Courier: "name, phone number" '); The console. The log (` students: ${student. The getName ()}, ${student. GetPhone ()} `); console.log(); }Copy the code

Observer model

Brief: Define a one-to-many dependency between objects such that whenever an object changes state, all dependent objects are notified and automatically updated.

Code examples:

// Observer pattern // defines a one-to-many dependency between objects so that whenever an object changes state, all dependent objects are notified and automatically updated. / / scene: Observer * update(String barName, Observable * addObserver(Observer OB) Adds an Observer * removeObserver(Observe OB) Deletes an Observer * Observers */ /** / function WxUser() {this.update = function(barName, Message) {console.log(' public id ${barName} : ${message} '); ** / function WxBar(name) {var obs = new Set(); this.addObserver = function(ob) { obs.add(ob); } this.removeObserver = function(ob) { obs.delete(ob); } this.notifyObservers = function(message) { for (let ob of obs) { ob.update(name, message); Var user1 = new WxUser(); var user2 = new WxUser(); Var wxBar = new wxBar; wxBar.addObserver(user1); wxBar.addObserver(user2); WxBar. NotifyObservers (" This is astute!" );Copy the code

The state pattern

Brief: When an object is allowed to change its behavior when its internal state changes, the object appears to have changed its class. In simple terms, an object has multiple states, and the object has several behaviors, and these behaviors are different for each state

Code examples:

// State mode allows an object to change its behavior when its internal state changes. The object looks like it has changed its class. // An object has multiple states, and the object has several behaviors. // Each state has different behaviors. File permissions (common users can only read, administrators can read and write, State * read() is readable * write() is writable * delete() is deleted */ /** Common user status constructor ** / function NomalUser() { This.read = function() {console.log(" readable "); } this.write = function() {console.log(" not writable "); } this.delete = function() {console.log(" not deleted "); }} /** / function Admin() {this.read = function() {console.log(" readable "); } this.write = function() {console.log(" writable "); } this.delete = function() {console.log(" not deleted "); }} /** SuperAdmin() {this.read = function() {console.log(" readable "); } this.write = function() {console.log(" writable "); } this.delete = function() {console.log(" console.log "); Function User(state) {this.setState = function(newState) {state = newState; } this.readFile = function() { state.read(); } this.writeFile = function() { state.write(); } this.deleteFile = function() { state.delete(); Var user = new user (new NomalUser()); user.readFile(); user.writeFile(); user.setState(new SuperAdmin()); user.readFile(); user.writeFile(); user.deleteFile();Copy the code

Memo mode

Brief: Three characters, originator, memo, and Memo Keeper. There are two interfaces exposed in the originator, one is used to package its state into a memo, and the other is used to restore its state through the memo guardian, which only saves the state of the originator, and maintains a memo in the memo guardian, which can be read and written.

Code examples:

// Set another object as the memo object, save the state of the object // scenario: Equipments (equipments) {this.setEquipments = function(newEquipments) {equipments (equipments) = function(newEquipments) { equipments = newEquipments; } this.getEquipments = function() { return equipments; }} /** equip bar () {var equipments = []; This.buyequipment = function(equipment) {console.log(' Bought equipment: ${equipment} '); equipments.push(equipment); } this.showequipments = function() {console. Log (" equipment purchased: ", equipments. Join (" ")); } this.getEquipmentsMemento = function() { return new EquipmentsMemento([...equipments]); } this.recoverEquipments = function(equipmentCaretaker) { equipments = equipmentCaretaker.getEquipmentsMemento().getEquipments(); } / / equip caretaker () {var equip = null; this.setEquipmentsMemento = function(newEquipmentsMemento) { equipmentsMemento = newEquipmentsMemento; } this.getEquipmentsMemento = function() { return equipmentsMemento; } // equip caretaker = new equipmentCaretaker (); Var equipmentBar = new equipmentBar (); / / buy equipment equipmentBar buyEquipment (" the blade of the endless "); EquipmentBar. BuyEquipment (" berserker shank armour "); / / save the current equipmentCaretaker. SetEquipmentsMemento (equipmentBar getEquipmentsMemento ()); / / bought a piece of unwanted equipment equipmentBar. BuyEquipment (" useless sticks "); equipmentBar.showEquipments(); // Recall console.log(" Player bought wrong, recall...") ); equipmentBar.recoverEquipments(equipmentCaretaker); equipmentBar.showEquipments();Copy the code

Parser pattern

Brevity: Given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language.

Code examples:

// Given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language. Function Context() {var tableName = null/** string */; var params = null/** object */; var wheres = null/** object */; var fields = null/** set */; this.setTableName = function(newTableName) { tableName = newTableName; } this.getTableName = function() { return tableName; } this.setParams = function(newParams) { params = newParams; } this.getParams = function() { return params; } this.setWheres = function(newWheres) { wheres = newWheres; } this.getWheres = function() { return wheres; } this.setFields = function(newFields) { fields = newFields; } this.getFields = function() { return fields; }} /** interpreter interface SQLExpression * string interpret(Context Context) */ /** insert SQL interpreter ** / function InsertSQLExpression() { this.interpret = function(context) { var params = context.getParams(); Var keys = "("; var allKey = Object.getOwnPropertyNames(params); allKey.forEach((key) => { keys += key + ","; }); keys = keys.substring(0, keys.length - 1); keys += ")"; Var values = "("; allKey.forEach((key) => { values += (typeof params[key] === 'string' ? `'${params[key]}'` : params[key]) + ","; }); values = values.substring(0, values.length - 1); values += ")"; return `insert into ${context.getTableName()} ${keys} values ${values}`; InsertSQLExpression = new insertSQLExpression (); var context = new Context(); context.setTableName("student"); context.setParams({ name: 'dcw', age: 22 }); var sql = insertSQLExpression.interpret(context); console.log(sql)Copy the code

Visitor pattern

Brief: Talk like a horse, talk like a horse

Code examples:

// Scene: When buying clothes, the waiter leads the boys to the boys' section, /** * extends Waiter ** / function YiChunWaiter() {** * extends Waiter ** / function YiChunWaiter() { this.accept = function(customer) { customer.visit(this); } // serverWoman this.serverwoman = function() {console.log(" Lead the ladies to the ladies' clothing section."); } // This. ServeMan = function() {console.log(" lead men to men's clothing."); ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **  { waiter.serverWoman(); }} /** ** / function ManCustomer() {this.visit = function(waiter) {waiter.serveman (); Var yichunWaiter = new yichunWaiter (); var womanCustomer = new WomanCustomer(); var manCustomer = new ManCustomer(); yichunWaiter.accept(womanCustomer); yichunWaiter.accept(manCustomer);Copy the code