全国免费咨询:

13245491521

VR图标白色 VR图标黑色
X

中高端软件定制开发服务商

与我们取得联系

13245491521     13245491521

2023-08-31_JavaScript设计模式:让你的代码像个天才!

您的位置:首页 >> 新闻 >> 行业资讯

JavaScript设计模式:让你的代码像个天才! 点击关注公众号,技术干货及时送达 你是否曾经在JavaScript代码中迷失过? 是否曾经感到自己的代码像一团乱麻? 别担心,这就是我们需要设计模式的时候了! 让我们一起探索这些神奇的模式,让你的代码变得像个天才! 序言 总体来说设计模式分为三大类: 创建型模式: 工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式: 适配器模式、装饰模式、代理模式、外观模式、桥接模式、组合模式、享元模式。 行为型模式: 策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 准备好了吗?让我们一起进入JavaScript设计模式的神奇世界,让你的代码变得像Tony Stark一样聪明! 工厂方法模式(Factory Method Pattern)工厂方法模式定义了一个创建对象的接口,但是由子类决定要实例化的类是哪一个。可以将对象的创建和使用分离,使得系统更加灵活。其代码示例如下: //定义一个抽象类 classAnimal{ //定义抽象方法speak,该方法必须在子类中被实现 speak(){ thrownewError('Thismethodmustbeimplemented.'); } } //实现具体的类 //实现具体的类Dog,继承自抽象类Animal classDogextendsAnimal{ speak(){ return'Woof!'; } } //实现具体的类Cat,继承自抽象类Animal classCatextendsAnimal{ speak(){ return'Meow!'; } } //实现工厂方法 classAnimalFactory{ createAnimal(animalType){ switch(animalType){ case'dog': returnnewDog(); case'cat': returnnewCat(); default: thrownewError(`Invalidanimaltype:${animalType}`); } } } //使用工厂方法创建对象 constanimalFactory=newAnimalFactory(); constdog=animalFactory.createAnimal('dog'); console.log(dog.speak());//Output:Woof! constcat=animalFactory.createAnimal('cat'); console.log(cat.speak());//Output:Meow! 抽象工厂模式(Abstract Factory Pattern)抽象工厂模式提供了一种封装一组具有相同主题的单个工厂的方式。它有一个接口,用于创建相关或依赖对象的家族,而不需要指定实际实现的类。其代码示例如下: //创建一组主题对象类型的抽象类 classAnimalFood{ provide(){ thrownewError('Thismethodmustbeimplemented.'); } } classAnimalToy{ provide(){ thrownewError('Thismethodmustbeimplemented.'); } } //创建一组具体代表家族的对象 classHighQualityDogFoodextendsAnimalFood{ provide(){ return'Highqualitydogfood'; } } classHighQualityDogToyextendsAnimalToy{ provide(){ return'Highqualitydogtoy'; } } classCheapCatFoodextendsAnimalFood{ provide(){ return'Cheapcatfood'; } } classCheapCatToyextendsAnimalToy{ provide(){ return'Cheapcattoy'; } } //创建一个抽象工厂 classAnimalProductsAbstractFactory{ createFood(){ thrownewError('Thismethodmustbeimplemented.'); } createToy(){ thrownewError('Thismethodmustbeimplemented.'); } } //创建具体工厂类 classHighQualityAnimalProductsFactoryextendsAnimalProductsAbstractFactory{ createFood(){ returnnewHighQualityDogFood(); } createToy(){ returnnewHighQualityDogToy(); } } classCheapAnimalProductsFactoryextendsAnimalProductsAbstractFactory{ createFood(){ returnnewCheapCatFood(); } createToy(){ returnnewCheapCatToy(); } } //使用具体工厂类来创建相关的对象 consthighQualityAnimalProductsFactory=newHighQualityAnimalProductsFactory(); console.log(highQualityAnimalProductsFactory.createFood().provide());//Output:Highqualitydogfood console.log(highQualityAnimalProductsFactory.createToy().provide());//Output:Highqualitydogtoy constcheapAnimalProductsFactory=newCheapAnimalProductsFactory(); console.log(cheapAnimalProductsFactory.createFood().provide());//Output:Cheapcatfood console.log(cheapAnimalProductsFactory.createToy().provide());//Output:Cheapcattoy 单例模式(Singleton Pattern)单例模式的目的是确保一个类只有一个实例,并为该实例提供全局访问点。其代码示例如下: classLogger{ constructor(){ if(!Logger.instance){ this.logs= Logger.instance=this; } returnLogger.instance; } log(message){ this.logs.push(message); console.log(`Logger:${message}`); } printLogCount(){ console.log(`Numberoflogs:${this.logs.length}`); } } //可以使用全局变量来访问实例 constlogger=newLogger(); Object.freeze(logger); //对于每个实例,输出应该是相同的 logger.log('Firstmessage');//Output:Logger:Firstmessage logger.printLogCount();//Output:Numberoflogs:1 constanotherLogger=newLogger();//此时返回一个已经存在的实例 anotherLogger.log('Secondmessage');//Output:Logger:Secondmessage anotherLogger.printLogCount();//Output:Numberoflogs:2 建造者模式(Builder Pattern)建造者模式是一种对象创建设计模式,它旨在通过一步步的构建流程来创建复杂对象。其代码示例如下: //创建Product类 classSandwich{ constructor(){ this.ingredients= } addIngredient(ingredient){ this.ingredients.push(ingredient); } toString(){ returnthis.ingredients.join(','); } } //创建一个建造者类 classSandwichBuilder{ constructor(){ this.sandwich=newSandwich(); } reset(){ this.sandwich=newSandwich(); } putMeat(meat){ this.sandwich.addIngredient(meat); } putCheese(cheese){ this.sandwich.addIngredient(cheese); } putVegetables(vegetables){ this.sandwich.addIngredient(vegetables); } getresult(){ returnthis.sandwich; } } //创建用户(director)使用的builder classSandwichMaker{ constructor(){ this.builder=newSandwichBuilder(); } createCheeseSteakSandwich(){ this.builder.reset(); this.builder.putMeat('ribeyesteak'); this.builder.putCheese('americancheese'); this.builder.putVegetables(['peppers','onions']); returnthis.builder.result; } } //建造一个三明治 constsandwichMaker=newSandwichMaker(); constsandwich=sandwichMaker.createCheeseSteakSandwich(); console.log(`Yoursandwich:${sandwich}`);//Output:Yoursandwich:ribeyesteak,americancheese,peppers,onions 原型模式(Prototype Pattern)原型模式(Prototype Pattern)是一种创建型设计模式,它可以用于创建对象的成本相对较高,但对于由相同属性的对象可以通过克隆来创建。原型模式将对象的创建过程和对象的使用过程分离,它通过克隆已有对象来创建新的对象,从而避免了昂贵的对象创建过程。在 JavaScript 中,原型模式的实现很容易,因为它天然支持对象的 clone(即浅拷贝)。 这是一个使用原型模式的示例代码: //创建一个原型对象 constcarPrototype={ wheels:4, color:'red', start(){ console.log('Startingthecar...'); }, stop(){ console.log('Stoppingthecar...'); }, }; //使用Object.create()方法克隆 constcar1=Object.create(carPrototype); console.log(car1);//Output:{} car1.wheels=6; console.log(car1.wheels);//Output:6 console.log(car1.color);//Output:red car1.start();//Output:Startingthecar... car1.stop();//Output:Stoppingthecar... //克隆另一个对象 constcar2=Object.create(carPrototype); console.log(car2);//Output:{} car2.color='blue'; console.log(car2.color);//Output:blue console.log(car2.wheels);//Output:4 car2.start();//Output:Startingthecar... car2.stop();//Output:Stoppingthecar... 在这个例子中,我们创建了一个名为carPrototype的原型对象。然后,我们通过Object.create()方法克隆了该原型对象。由于我们使用了浅拷贝,所以在使用前我们可以修改对象的属性,并且car2和car1对象的start()和stop()方法是相同的,因为它们来自相同的原型对象。 原型模式的一个优点是它提供了一种简便的方式来创建具有相同属性的对象。它可以减少重复代码,并且在创建对象时节省时间和资源。当然,它也有一些缺点,例如在使用深拷贝时可能会出现意想不到的问题,因为深拷贝将复制所有属性,而这些属性还可能引用其他对象。 适配器模式(Adapter Pattern)适配器模式(Adapter Pattern)是一种结构型设计模式,它允许将不兼容的对象包装在适配器中,从而使它们能够在一起工作。以下是适配器模式的代码示例: //目标接口 classTarget{ request(){ console.log('Target:请求已被调用'); } } //需要适配的类 classAdaptee{ specificRequest(){ console.log('Adaptee方法已被访问'); } } //适配器类,将Adaptee转换为Target classAdapterextendsTarget{ constructor(adaptee){ super(); this.adaptee=adaptee; } request(){ this.adaptee.specificRequest(); } } //使用适配器将客户端与Adaptee解耦 constclient=newAdapter(newAdaptee()); client.request();//Output:Adaptee方法已被访问 在上述代码中,我们有一个目标接口Target和一个需要适配的类Adaptee。我们通过创建一个适配器类Adapter将Adaptee转换为Target,并使用适配器进行通信的客户端client调用request()方法,从而实现Adaptee的功能。 装饰模式(Decorator Pattern)装饰模式(Decorator Pattern)是一种结构型设计模式,它允许在不影响其他对象的情况下,动态地将功能添加到对象中。以下是装饰模式的代码示例: //抽象组件类 classComponent{ operation(){ console.log('Component:基础操作'); } } //具体组件类 classConcreteComponentextendsComponent{ operation(){ console.log('ConcreteComponent:具体操作'); } } //抽象装饰器类 classDecoratorextendsComponent{ constructor(component){ super(); this.component=component; } operation(){ this.component.operation(); } } //具体装饰器类 classConcreteDecoratorAextendsDecorator{ operation(){ super.operation(); console.log('ConcreteDecoratorA:添加操作'); } } classConcreteDecoratorBextendsDecorator{ operation(){ super.operation(); console.log('ConcreteDecoratorB:添加操作'); } } //使用装饰器组合对象 constcomponent=newConcreteComponent(); constdecoratorA=newConcreteDecoratorA(component); constdecoratorB=newConcreteDecoratorB(decoratorA); decoratorB.operation(); 在上述代码中,我们有一个抽象组件类Component和一个具体组件类ConcreteComponent。我们创建了两个装饰器类ConcreteDecoratorA和ConcreteDecoratorB,它们都继承自Decorator类,并且可以添加新的行为到被装饰的对象上。最后,我们实例化ConcreteComponent类,将其封装在ConcreteDecoratorA和ConcreteDecoratorB类中,最终组成一个具有多个操作的对象。 代理模式(Proxy Pattern)代理模式(Proxy Pattern)是一种结构型设计模式,它允许在访问对象时提供一个占位符或代理,以控制对对象的访问。以下是代理模式的代码示例: //主题接口 classSubject{ request(){ console.log('Subject:处理请求'); } } //真实主题类 classRealSubjectextendsSubject{ request(){ console.log('RealSubject:处理请求'); } } //代理类 classProxyextendsSubject{ constructor(realSubject){ super(); this.realSubject=realSubject; } request(){ if(this.checkAccess()){ this.realSubject.request(); this.logAccess(); } } checkAccess(){ console.log('Proxy:检查访问权限'); returntrue; } logAccess(){ console.log('Proxy:记录访问日志'); } } //使用代理访问真实对象 constrealSubject=newRealSubject(); constproxy=newProxy(realSubject); proxy.request(); 在上述代码中,我们有一个主题接口Subject和一个真实主题类RealSubject。我们创建了一个代理类Proxy,它封装了一个真实主题,并在对其进行访问时提供了额外的功能,例如检查访问权限和记录访问日志。我们通过实例化RealSubject类并封装它在Proxy类中,最终通过代理访问真实的主题对象。 外观模式(Facade Pattern)外观模式(Facade Pattern)是一种结构型设计模式,它为一组复杂的子系统提供了一个更简单的接口。以下是外观模式的代码示例: //子系统1 classSubsystem1{ operation1(){ console.log('Subsystem1:执行操作1'); } } //子系统2 classSubsystem2{ operation2(){ console.log('Subsystem2:执行操作2'); } } //外观类 classFacade{ constructor(){ this.subsystem1=newSubsystem1(); this.subsystem2=newSubsystem2(); } operation(){ this.subsystem1.operation1(); this.subsystem2.operation2(); } } //客户端代码 constfacade=newFacade(); facade.operation();//Output:Subsystem1:执行操作1,Subsystem2:执行操作2 在上述代码中,我们有两个子系统Subsystem1和Subsystem2,它们都提供了复杂的操作。我们通过使用外观模式创建了一个Facade类,它的接口更加简单,通过组合Subsystem1和Subsystem2对象的操作来实现其功能。最后,我们实例化Facade类并调用操作方法operation(),完成了复杂的功能操作。 桥接模式(Bridge Pattern)桥接模式(Bridge Pattern)是一种结构型设计模式,它将一个对象的抽象和实现分离开来,从而使它们都可以独立变化。以下是桥接模式的示例代码: //实现类接口 classImplementor{ operationImpl(){ console.log('Implementor:执行操作'); } } //抽象类 classAbstraction{ constructor(implementor){ this.implementor=implementor; } operation(){ this.implementor.operationImpl(); } } //扩展抽象类 classRefinedAbstractionextendsAbstraction{ otherOperation(){ console.log('RefinedAbstraction:其他操作'); } } //使用桥接模式 constimplementor=newImplementor(); constabstraction=newAbstraction(implementor); abstraction.operation();//Output:Implementor:执行操作 constrefinedAbstraction=newRefinedAbstraction(implementor); refinedAbstraction.operation();//Output:Implementor:执行操作 refinedAbstraction.otherOperation();//Output:RefinedAbstraction:其他操作 在上述代码中,我们有一个实现类接口Implementor和一个抽象类Abstraction。我们通过创建一个扩展抽象类RefinedAbstraction来扩展抽象类的功能,它们都使用了某个实现类的实例对象。然后,我们实例化Implementor并通过在Abstraction和RefinedAbstraction类的声明中传递Implementor对象来创建两个具有不同行为的对象。通过将实现和抽象分离开来,我们可以随意地组合实现与抽象,并使其易于扩展。 组合模式(Composite Pattern)组合模式(Composite Pattern)是一种结构型设计模式,它使用树形结构来表示对象的部分-整体层次结构,并使用户能够以统一的方式处理单个对象和对象组合。以下是组合模式的示例代码: //抽象构件 classComponent{ constructor(name){ this.name=name; } operation(){ console.log(`Component${this.name}:执行操作`); } add(component){ console.log('Component:不支持的操作'); } remove(component){ console.log('Component:不支持的操作'); } getChild(index){ console.log('Component:不支持的操作'); } } //叶子节点 classLeafextendsComponent{ constructor(name){ super(name); } } //树枝节点 classCompositeextendsComponent{ constructor(name){ super(name); this.children= } add(component){ this.children.push(component); } remove(component){ constindex=this.children.indexOf(component); if(index=0){ this.children.splice(index,1); } } getChild(index){ returnthis.children[index]; } } //使用组合模式 constroot=newComposite('根'); constbranch1=newComposite('树枝1'); constbranch2=newComposite('树枝2'); constleaf1=newLeaf('叶子1'); constleaf2=newLeaf('叶子2'); constleaf3=newLeaf('叶子3'); root.add(branch1); root.add(branch2); branch1.add(leaf1); branch1.add(leaf2); branch2.add(leaf3); root.operation();//Output:Component根:执行操作 branch1.operation();//Output:Component树枝1:执行操作 branch1.remove(leaf2); branch2.operation();//Output:Component树枝2:执行操作 root.getChild(0).operation();//Output:Component树枝1:执行操作 在上述代码中,我们有一个抽象构件Component,通过创建两个具体构建Leaf和Composite来扩展抽象构件的功能。Composite保持着一个子对象的数组,并实现了在包含其他组件的能力。然后,我们使用所有这些组件来建立一个树形结构, 父节点模型是Component对象,而子节点可以是Component对象或Composite对象。最终,我们可以通过调用操作方法来进行操作。 享元模式(Flyweight Pattern)享元模式(Flyweight Pattern)是一种结构型设计模式,它通过共享对象来最小化内存使用和类实例化的数量。以下是享元模式的示例代码: //Flyweight工厂类 classFlyweightFactory{ constructor(){ this.flyweights= } getFlyweight(key){ if(!this.flyweights[key]){ this.flyweights[key]=newConcreteFlyweight(key); } returnthis.flyweights[key]; } } //具体Flyweight类 classConcreteFlyweight{ constructor(key){ this.key= } operation(){ console.log(`ConcreteFlyweight${this.key}:执行操作`); } } //使用享元模式 constfactory=newFlyweightFactory(); constflyweight1=factory.getFlyweight('key'); constflyweight2=factory.getFlyweight('key'); flyweight1.operation();//Output:ConcreteFlyweightkey:执行操作 flyweight2.operation();//Output:ConcreteFlyweightkey:执行操作 console.log(flyweight1===flyweight2);//Output:true 在上述代码中,我们有一个 Flyweight 工厂类FlyweightFactory,用于创建并管理基础的共享ConcreteFlyweight对象。ConcreteFlyweight对象包含需要共享的数据或状态。我们实例化FlyweightFactory,并通过在FlyweightFactory的getFlyweight()方法中获取对象,以及通过多个对象来验证是否共享相同的对象。最终,结果显示flyweight1跟flyweight2指向同一个对象,由此证明了共享对象的概念。 策略模式(Strategy Pattern)策略模式是一种设计模式,它定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。策略模式让算法独立于使用它的客户端而独立变化。这种模式属于行为型模式。 示例代码如下: classStrategy{ constructor(name){ this.name=name; } execute(){} } classStrategyAextendsStrategy{ execute(){ console.log('ExecutingstrategyA'); } } classStrategyBextendsStrategy{ execute(){ console.log('ExecutingstrategyB'); } } classContext{ constructor(strategy){ this.strategy=strategy; } executeStrategy(){ this.strategy.execute(); } } letcontext=newContext(newStrategyA('A')); context.executeStrategy();//ExecutingstrategyA context.strategy=newStrategyB('B'); context.executeStrategy();//ExecutingstrategyB 模板方法模式(Template Method Pattern)模板方法模式是一种行为设计模式。它定义了一个操作中的算法骨架,将某些步骤延迟到子类中实现。模板方法使得子类可以不改变算法的结构即可重新定义该算法的某些特定步骤。 示例代码: classGame{ setup(){} start(){ this.setup(); this.play(); this.finish(); } play(){} finish(){} } classChessextendsGame{ setup(){ console.log('Settingupchessgame'); } play(){ console.log('Playingchess'); } finish(){ console.log('Finishingchessgame'); } } classTicTacToeextendsGame{ setup(){ console.log('SettingupTicTacToegame'); } play(){ console.log('PlayingTicTacToe'); } finish(){ console.log('FinishingTicTacToegame'); } } letgame=newChess(); game.start(); game=newTicTacToe(); game.start(); 观察者模式(Observer Pattern)观察者模式是一种行为设计模式,其中对象之间存在一对多的依赖关系。当一个对象的状态发生变化时,它的所有依赖者都得到通知并自动更新。观察者模式将对象之间的关系解耦,使得它们可以独立变化。 示例代码: classSubject{ constructor(){ this.observers= } attach(observer){ this.observers.push(observer); } detach(observer){ constindex=this.observers.indexOf(observer); if(index-1){ this.observers.splice(index,1); } } notify(){ for(constobserverofthis.observers){ observer.update(this); } } } classObserver{ update(subject){} } classConcreteSubjectextendsSubject{ constructor(state){ super(); this.state=state; } set_state(state){ this.state=state; this.notify(); } get_state(){ returnthis.state; } } classConcreteObserverextendsObserver{ update(subject){ console.log(`Gotupdatedvalue:${subject.get_state()}`); } } letsubject=newConcreteSubject('initialstate'); letobserver=newConcreteObserver(); subject.attach(observer); subject.set_state('newstate'); 迭代器模式(Iterator Pattern)迭代器模式是一种行为设计模式,它提供了一种方式来顺序访问集合对象中的元素。迭代器模式将遍历集合的责任交给迭代器,而不是集合自己。这样就可以将集合的实现和遍历算法的实现分离开来,从而提供更好的灵活性。 示例代码: classIterator{ constructor(items){ this.items=items; this.cursor=0; } has_next(){ returnthis.cursorthis.items.length; } next(){ constitem=this.items[this.cursor]; this.cursor+=1; returnitem; } } classCollection{ constructor(){ this.items= } add_item(item){ this.items.push(item); } iterator(){ returnnewIterator(this.items); } } constcollection=newCollection(); collection.add_item('item1'); collection.add_item('item2'); collection.add_item('item3'); constiterator=collection.iterator(); while(iterator.has_next()){ console.log(iterator.next()); } 责任链模式(Chain of Responsibility)责任链模式(Chain of Responsibility)是一种行为型设计模式。它可以让多个对象都有机会处理请求,从而避免将请求的发送者和接收者耦合在一起。将这些对象连成一个链,并沿着这条链传递请求,直到有一个对象处理它为止。 实现方式: classHandler{ constructor(){ this.nextHandler=null; } setNextHandler(handler){ this.nextHandler=handler; } handleRequest(request){ if(this.nextHandler!==null){ returnthis.nextHandler.handleRequest(request); } returnnull; } } classConcreteHandlerAextendsHandler{ handleRequest(request){ if(request==='A'){ return`HandleRequest${request}`; } returnsuper.handleRequest(request); } } classConcreteHandlerBextendsHandler{ handleRequest(request){ if(request==='B'){ return`HandleRequest${request}`; } returnsuper.handleRequest(request); } } classConcreteHandlerCextendsHandler{ handleRequest(request){ if(request==='C'){ return`HandleRequest${request}`; } returnsuper.handleRequest(request); } } consthandlerA=newConcreteHandlerA(); consthandlerB=newConcreteHandlerB(); consthandlerC=newConcreteHandlerC(); handlerA.setNextHandler(handlerB); handlerB.setNextHandler(handlerC); console.log(handlerA.handleRequest('A'));//HandleRequestA console.log(handlerA.handleRequest('B'));//HandleRequestB console.log(handlerA.handleRequest('C'));//HandleRequestC console.log(handlerA.handleRequest('D'));//null 命令模式(Command)命令模式(Command)是一种行为型设计模式,它将请求或操作封装到一个对象中,从而允许你将请求或操作的发起者与具体执行者解耦。命令模式可以将请求或操作参数化,甚至在运行时动态地组合命令 实现方式: classCommand{ constructor(receiver){ this.receiver=receiver; } execute(){ thrownewError('Youhavetoimplementthemethodexecute!'); } } classConcreteCommandAextendsCommand{ execute(){ this.receiver.actionA(); } } classConcreteCommandBextendsCommand{ execute(){ this.receiver.actionB(); } } classReceiver{ actionA(){ console.log('ReceiverActionA.'); } actionB(){ console.log('ReceiverActionB.'); } } classInvoker{ constructor(){ this.commands=newMap(); } setCommand(key,command){ this.commands.set(key,command); } executeCommand(key){ constcommand=this.commands.get(key); if(!command){ console.log(`Command${key}isnotfound.`); return; } command.execute(); } } constreceiver=newReceiver(); constinvoker=newInvoker(); invoker.setCommand('A',newConcreteCommandA(receiver)); invoker.setCommand('B',newConcreteCommandB(receiver)); invoker.executeCommand('A');//ReceiverActionA. invoker.executeCommand('B');//ReceiverActionB. 备忘录模式(Memento)备忘录模式(Memento)是一种行为型设计模式,它允许你在不暴露对象实现细节的情况下保存和恢复对象的状态。备忘录模式涉及到三个角色:备忘录(Memento), 发起人(Originator), 管理者(Caretaker)。 实现方式: classMemento{ constructor(state){ this.state=state; } getState(){ returnthis.state; } } classOriginator{ constructor(state){ this.state=state; } setState(state){ this.state=state; } createMemento(){ returnnewMemento(this.state); } restoreMemento(memento){ this.state=memento.getState(); } getState(){ returnthis.state; } } classCaretaker{ constructor(){ this.mementos= } addMemento(memento){ this.mementos.push(memento); } getMemento(index){ returnthis.mementos[index]; } } constoriginator=newOriginator('StateA'); constcaretaker=newCaretaker(); //Savestate caretaker.addMemento(originator.createMemento()); //changestate originator.setState('StateB'); console.log(`CurrentState:${originator.getState()}`); //Restorestate originator.restoreMemento(caretaker.getMemento(0)); console.log(`CurrentState:${originator.getState()}`); 状态模式(State)状态模式(State)是一种行为型设计模式,它允许对象在其内部状态发生改变时改变其行为。状态模式通过将每个状态封装在一个类中,使得对于该状态进行的任何操作都可以在该类中处理。从而将状态转换的代码从主要业务逻辑中抽离出来,避免出现大量 if-else 语句。 实现方式: classContext{ constructor(){ this.state=newConcreteStateA(this); } setState(state){ this.state=state; } request(){ this.state.handle(); } } classState{ constructor(context){ this.context=context; } handle(){ thrownewError('Youhavetoimplementthemethodhandle!'); } } classConcreteStateAextendsState{ handle(){ console.log('HandleStateA'); this.context.setState(newConcreteStateB(this.context)); } } classConcreteStateBextendsState{ handle(){ console.log('HandleStateB'); this.context.setState(newConcreteStateA(this.context)); } } constcontext=newContext(); context.request();//HandleStateA context.request();//HandleStateB context.request();//HandleStateA 访问者模式(Visitor)访问者模式(Visitor)是一种行为型设计模式,它允许你将算法封装在一个或多个访问者类中,从而让你在不改变各个元素类接口的前提下定义作用于这些元素的新操作。 实现方式: classElement{ accept(visitor){ thrownewError('Youhavetoimplementthemethodaccept!'); } } classConcreteElementAextendsElement{ accept(visitor){ visitor.visitConcreteElementA(this); } operationA(){ console.log('OperationAofConcreteElementA.'); } } classConcreteElementBextendsElement{ accept(visitor){ visitor.visitConcreteElementB(this); } operationB(){ console.log('OperationBofConcreteElementB.'); } } classVisitor{ visitConcreteElementA(element){ console.log(`VisitConcreteElementAwith${element.operationA()}`); } visitConcreteElementB(element){ console.log(`VisitConcreteElementBwith${element.operationB()}`); } } constelementA=newConcreteElementA(); constelementB=newConcreteElementB(); constvisitor=newVisitor(); elementA.accept(visitor); elementB.accept(visitor); 中介者模式(Mediator)中介者模式(Mediator)是一种行为型设计模式,它允许你减少组件之间的直接依赖关系,将它们通过一个中介者对象进行交互。通过避免在组件之间显式引用彼此,中介者可以让你更容易地复用组件。 实现方式: classMediator{ constructor(){ this.components=newSet(); } register(component){ component.mediator=this; this.components.add(component); } notify(sender,event){ this.components.forEach((component)={ if(component!==sender){ component.receive(sender,event); } } } classComponent{ constructor(name){ this.name=name; this.mediator=null; } send(event){ console.log(`Sendevent${event}from${this.name}`); this.mediator.notify(this,event); } receive(sender,event){ console.log(`Receiveevent${event}from${sender.name}by${this.name}`); } } constmediator=newMediator(); constcomponentA=newComponent('ComponentA'); constcomponentB=newComponent('ComponentB'); constcomponentC=newComponent('ComponentC'); mediator.register(componentA); mediator.register(componentB); mediator.register(componentC); componentA.send('Hello');//SendeventHellofromComponentA,ReceiveeventHellofromComponentAbyComponentB,ReceiveeventHellofromComponentAbyComponentC 解释器模式(Interpreter)解释器模式(Interpreter)是一种行为型设计模式,它能够将一种语言(通常是一种编程语言)或者表达式的文法表示为解析树,并定义一个解释器,使用该解释器来解释这个语言或者表达式。 实现方式: classContext{ constructor(input){ this.input=input; this.output=0; } } classExpression{ interpreter(context){ thrownewError('Youhavetoimplementthemethodinterpreter!'); } } classThousandExpressionextendsExpression{ interpreter(context){ conststr=context.input; if(str.startsWith('M')){ context.output+=1000; context.input=str.slice(1); } } } classHundredExpressionextendsExpression{ interpreter(context){ conststr=context.input; if(str.startsWith('C')){ context.output+=100; context.input=str.slice(1); }elseif(str.startsWith('CD')){ context.output+=400; context.input=str.slice(2); }elseif(str.startsWith('CM')){ context.output+=900; context.input=str.slice(2); } } } classTenExpressionextendsExpression{ interpreter(context){ conststr=context.input; if(str.startsWith('X')){ context.output+=10; context.input=str.slice(1); }elseif(str.startsWith('XL')){ context.output+=40; context.input=str.slice(2); }elseif(str.startsWith('XC')){ context.output+=90; context.input=str.slice(2); } } } classOneExpressionextendsExpression{ interpreter(context){ conststr=context.input; if(str.startsWith('I')){ context.output+=1; context.input=str.slice(1); }elseif(str.startsWith('IV')){ context.output+=4; context.input=str.slice(2); }elseif(str.startsWith('V')){ context.output+=5; context.input=str.slice(1); }elseif(str.startsWith('IX')){ context.output+=9; context.input=str.slice(2); } } } classInterpreter{ staticparse(roman){ constcontext=newContext(roman); consttree=[ newThousandExpression(), newHundredExpression(), newTenExpression(), newOneExpression(), tree.forEach((expression)=expression.interpreter(context)); returncontext.output; } } console.log(Interpreter.parse('CDXLVIII'));//448 总结现在你已经掌握了这些设计模式,是时候让你的代码从“我不知道这是什么”变成“这是我写的,我知道它是什么了”了!快去展示你的新技能吧,让你的同事们惊叹不已! 如果文章对你有帮助的话欢迎 「关注+点赞+收藏」 阅读原文

上一篇:2023-02-17_硅谷大佬逃离谷歌发长文控诉:公司已迷失方向,员工被困在系统里 下一篇:2024-08-23_市场很卷、用户在变 , 企业营销如何进入next level

TAG标签:

12
网站开发网络凭借多年的网站建设经验,坚持以“帮助中小企业实现网络营销化”为宗旨,累计为4000多家客户提供品质建站服务,得到了客户的一致好评。如果您有网站建设网站改版域名注册主机空间手机网站建设网站备案等方面的需求...
请立即点击咨询我们或拨打咨询热线:13245491521 13245491521 ,我们会详细为你一一解答你心中的疑难。
项目经理在线

相关阅读 更多>>

猜您喜欢更多>>

我们已经准备好了,你呢?
2022我们与您携手共赢,为您的企业营销保驾护航!

不达标就退款

高性价比建站

免费网站代备案

1对1原创设计服务

7×24小时售后支持

 

全国免费咨询:

13245491521

业务咨询:13245491521 / 13245491521

节假值班:13245491521()

联系地址:

Copyright © 2019-2025      ICP备案:沪ICP备19027192号-6 法律顾问:律师XXX支持

在线
客服

技术在线服务时间:9:00-20:00

在网站开发,您对接的直接是技术员,而非客服传话!

电话
咨询

13245491521
7*24小时客服热线

13245491521
项目经理手机

微信
咨询

加微信获取报价