js设计模式-常见的13种

在JavaScript中,有多种常见的设计模式可供使用。以下是13种常见的JavaScript设计模式:

JavaScript设计模式

  1. 单例模式(Singleton Pattern)
  2. 工厂模式(Factory Pattern)
  3. 抽象工厂模式(Abstract Factory Pattern)
  4. 原型模式(Prototype Pattern)
  5. 建造者模式(Builder Pattern)
  6. 适配器模式(Adapter Pattern)
  7. 装饰器模式(Decorator Pattern)
  8. 观察者模式(Observer Pattern)
  9. 发布-订阅模式(Publish-Subscribe Pattern)
  10. 策略模式(Strategy Pattern)
  11. 状态模式(State Pattern)
  12. 代理模式(Proxy Pattern)
  13. 迭代器模式(Iterator Pattern)

简要说明

每种设计模式都有其独特的特点和用途,下面是对每种设计模式的简要说明:

  1. 单例模式 (Singleton Pattern):
    单例模式用于限制一个类只有一个实例,并提供一个全局访问点。

  2. 工厂模式 (Factory Pattern):
    工厂模式通过使用工厂方法创建对象,而不是直接调用构造函数来创建对象。

  3. 抽象工厂模式 (Abstract Factory Pattern):
    抽象工厂模式提供了一种创建相关对象的接口,而无需指定具体类。

  4. 原型模式 (Prototype Pattern):
    原型模式基于现有对象克隆创建新对象,避免了直接实例化。

  5. 建造者模式 (Builder Pattern):
    建造者模式用于创建复杂对象,通过一步一步地构建对象来实现。

  6. 适配器模式 (Adapter Pattern):
    适配器模式用于将不兼容的接口转换为可兼容的接口。

  7. 装饰器模式 (Decorator Pattern):
    装饰器模式允许在不修改原始对象的情况下给对象添加新功能。

  8. 观察者模式 (Observer Pattern):
    观察者模式定义了一种一对多的依赖关系,使得多个观察者对象可以同时监听一个主题对象。

  9. 发布-订阅模式 (Publish-Subscribe Pattern):
    发布-订阅模式允许多个订阅者订阅特定事件,当事件发生时,发布者会通知所有订阅者。

  10. 策略模式 (Strategy Pattern):
    策略模式定义了一系列可以互相替换的算法,并使得算法的选择与使用独立于客户端。

  11. 状态模式 (State Pattern):
    状态模式允许对象在内部状态改变时改变其行为,使对象看起来似乎修改了其类。

  12. 代理模式 (Proxy Pattern):
    代理模式提供了一个代理对象来控制对实际对象的访问,并可以通过代理对象添加额外的功能。

  13. 迭代器模式 (Iterator Pattern):
    迭代器模式提供一种访问聚合对象元素的方法,而不需要暴露聚合对象的内部结构。

这些设计模式可以帮助您更好地组织和设计JavaScript代码,提高代码的可维护性和可扩展性。具体使用哪种设计模式取决于问题的性质和需求。

详细代码说明:

以下是对每种设计模式的详细代码说明:

  1. 单例模式 (Singleton Pattern):
var Singleton = (function () {var instance;function createInstance() {var object = new Object("I am the instance");return object;}return {getInstance: function () {if (!instance) {instance = createInstance();}return instance;},};
})();var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();console.log(instance1 === instance2); // Output: true
  1. 工厂模式 (Factory Pattern):
function ShapeFactory() {}ShapeFactory.prototype.createShape = function (type) {if (type === "circle") {return new Circle();} else if (type === "rectangle") {return new Rectangle();} else if (type === "triangle") {return new Triangle();}
};function Circle() {this.type = "circle";
}function Rectangle() {this.type = "rectangle";
}function Triangle() {this.type = "triangle";
}var factory = new ShapeFactory();
var circle = factory.createShape("circle");
var rectangle = factory.createShape("rectangle");
var triangle = factory.createShape("triangle");console.log(circle.type); // Output: circle
console.log(rectangle.type); // Output: rectangle
console.log(triangle.type); // Output: triangle
  1. 抽象工厂模式 (Abstract Factory Pattern):
function FurnitureFactory() {}FurnitureFactory.prototype.createChair = function () {throw new Error("This method should be overridden");
};FurnitureFactory.prototype.createTable = function () {throw new Error("This method should be overridden");
};function ModernFurnitureFactory() {}ModernFurnitureFactory.prototype = Object.create(FurnitureFactory.prototype);
ModernFurnitureFactory.prototype.constructor = ModernFurnitureFactory;ModernFurnitureFactory.prototype.createChair = function () {return new ModernChair();
};ModernFurnitureFactory.prototype.createTable = function () {return new ModernTable();
};function VictorianFurnitureFactory() {}VictorianFurnitureFactory.prototype = Object.create(FurnitureFactory.prototype);
VictorianFurnitureFactory.prototype.constructor = VictorianFurnitureFactory;VictorianFurnitureFactory.prototype.createChair = function () {return new VictorianChair();
};VictorianFurnitureFactory.prototype.createTable = function () {return new VictorianTable();
};function ModernChair() {this.type = "modern chair";
}function ModernTable() {this.type = "modern table";
}function VictorianChair() {this.type = "victorian chair";
}function VictorianTable() {this.type = "victorian table";
}var modernFactory = new ModernFurnitureFactory();
var modernChair = modernFactory.createChair();
var modernTable = modernFactory.createTable();var victorianFactory = new VictorianFurnitureFactory();
var victorianChair = victorianFactory.createChair();
var victorianTable = victorianFactory.createTable();console.log(modernChair.type); // Output: modern chair
console.log(modernTable.type); // Output: modern table
console.log(victorianChair.type); // Output: victorian chair
console.log(victorianTable.type); // Output: victorian table
  1. 原型模式 (Prototype Pattern):
function Shape() {}Shape.prototype.clone = function () {throw new Error("This method should be overridden");
};function Circle(radius) {this.radius = radius;
}Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;Circle.prototype.clone = function () {return new Circle(this.radius);
};var circle = new Circle(5);
var clonedCircle = circle.clone();console.log(clonedCircle.radius); // Output: 5
  1. 建造者模式 (Builder Pattern):
function Car() {this.color = "";this.model = "";this.engine = "";
}function CarBuilder() {this.car = new Car();
}CarBuilder.prototype.setColor = function (color) {this.car.color = color;return this;
};CarBuilder.prototype.setModel = function (model) {this.car.model = model;return this;
};CarBuilder.prototype.setEngine = function (engine) {this.car.engine = engine;return this;
};CarBuilder.prototype.build = function () {return this.car;
};var car = new CarBuilder().setColor("red").setModel("sedan").setEngine("V8").build();console.log(car.color); // Output: red
console.log(car.model); // Output: sedan
console.log(car.engine); // Output: V8
  1. 适配器模式 (Adapter Pattern):
function MediaPlayer() {}MediaPlayer.prototype.play = function (audioType, fileName) {throw new Error("This method should be overridden");
};function AudioPlayer() {}AudioPlayer.prototype = Object.create(MediaPlayer.prototype);
AudioPlayer.prototype.constructor = AudioPlayer;AudioPlayer.prototype.play = function (audioType, fileName) {if (audioType === "mp3") {console.log("Playing mp3 file: " + fileName);} else {throw new Error("Unsupported audio type: " + audioType);}
};function MediaAdapter(audioType) {if (audioType === "mp3") {this.audioPlayer = new AudioPlayer();}
}MediaAdapter.prototype.play = function (audioType, fileName) {if (audioType === "mp3") {this.audioPlayer.play(audioType, fileName);} else {throw new Error("Unsupported audio type: " + audioType);}
};function AudioPlayerAdapter() {}AudioPlayerAdapter.prototype = Object.create(MediaPlayer.prototype);
AudioPlayerAdapter.prototype.constructor = AudioPlayerAdapter;AudioPlayerAdapter.prototype.play = function (audioType, fileName) {if (audioType === "mp3") {var mediaAdapter = new MediaAdapter(audioType);mediaAdapter.play(audioType, fileName);} else {throw new Error("Unsupported audio type: " + audioType);}
};var audioPlayer = new AudioPlayerAdapter();
audioPlayer.play("mp3", "song.mp3"); // Output: Playing mp3 file: song.mp3
  1. 装饰器模式 (Decorator Pattern):
function Pizza() {}Pizza.prototype.getDescription = function () {throw new Error("This method should be overridden");
};Pizza.prototype.cost = function () {throw new Error("This method should be overridden");
};function MargheritaPizza() {}MargheritaPizza.prototype = Object.create(Pizza.prototype);
MargheritaPizza.prototype.constructor = MargheritaPizza;MargheritaPizza.prototype.getDescription = function () {return "Margherita Pizza";
};MargheritaPizza.prototype.cost = function () {return 10;
};function PizzaDecorator(pizza) {this.pizza = pizza;
}PizzaDecorator.prototype.getDescription = function () {return this.pizza.getDescription();
};PizzaDecorator.prototype.cost = function () {return this.pizza.cost();
};function ExtraCheeseDecorator(pizza) {PizzaDecorator.call(this, pizza);
}ExtraCheeseDecorator.prototype = Object.create(PizzaDecorator.prototype);
ExtraCheeseDecorator.prototype.constructor = ExtraCheeseDecorator;ExtraCheeseDecorator.prototype.getDescription = function () {return this.pizza.getDescription() + ", Extra Cheese";
};ExtraCheeseDecorator.prototype.cost = function () {return this.pizza.cost() + 2;
};var margheritaPizza = new MargheritaPizza();
var extraCheesePizza = new ExtraCheeseDecorator(margheritaPizza);console.log(extraCheesePizza.getDescription()); // Output: Margherita Pizza, Extra Cheese
console.log(extraCheesePizza.cost()); // Output: 12
  1. 观察者模式 (Observer Pattern):
function Subject() {this.observers = [];
}Subject.prototype.subscribe = function (observer) {this.observers.push(observer);
};Subject.prototype.unsubscribe = function (observer) {var index = this.observers.indexOf(observer);if (index !== -1) {this.observers.splice(index, 1);}
};Subject.prototype.notify = function () {for (var i = 0; i < this.observers.length; i++) {this.observers[i].update();}
};function Observer(name) {this.name = name;
}Observer.prototype.update = function () {console.log(this.name + " received an update");
};var subject = new Subject();var observer1 = new Observer("Observer 1");
var observer2 = new Observer("Observer 2");
var observer3 = new Observer("Observer 3");subject.subscribe(observer1);
subject.subscribe(observer2);
subject.subscribe(observer3);subject.notify();
// Output: Observer 1 received an update
// Output: Observer 2 received an update
// Output: Observer 3 received an update
  1. 发布-订阅模式 (Publish-Subscribe Pattern):
function PubSub() {this.subscribers = {};
}PubSub.prototype.subscribe = function (event, callback) {if (!this.subscribers[event]) {this.subscribers[event] = [];}this.subscribers[event].push(callback);
};PubSub.prototype.unsubscribe = function (event,callback) {if (this.subscribers[event]) {var index = this.subscribers[event].indexOf(callback);if (index !== -1) {this.subscribers[event].splice(index, 1);}}
};PubSub.prototype.publish = function (event, data) {if (this.subscribers[event]) {this.subscribers[event].forEach(function (callback) {callback(data);});}
};var pubSub = new PubSub();var callback1 = function (data) {console.log("Callback 1 received data: " + data);
};var callback2 = function (data) {console.log("Callback 2 received data: " + data);
};pubSub.subscribe("event1", callback1);
pubSub.subscribe("event1", callback2);pubSub.publish("event1", "Hello World");
// Output: Callback 1 received data: Hello World
// Output: Callback 2 received data: Hello WorldpubSub.unsubscribe("event1", callback2);pubSub.publish("event1", "Hello Again");
// Output: Callback 1 received data: Hello Again10. 状态模式 (State Pattern):```javascript
function TrafficLight() {this.currentState = new RedLightState(this);
}TrafficLight.prototype.changeState = function (state) {this.currentState = state;
};TrafficLight.prototype.start = function () {this.currentState.start();
};function RedLightState(trafficLight) {this.trafficLight = trafficLight;
}RedLightState.prototype.start = function () {console.log("Red Light - Stop");this.trafficLight.changeState(new GreenLightState(this.trafficLight));
};function GreenLightState(trafficLight) {this.trafficLight = trafficLight;
}GreenLightState.prototype.start = function () {console.log("Green Light - Go");this.trafficLight.changeState(new YellowLightState(this.trafficLight));
};function YellowLightState(trafficLight) {this.trafficLight = trafficLight;
}YellowLightState.prototype.start = function () {console.log("Yellow Light - Prepare to Stop");this.trafficLight.changeState(new RedLightState(this.trafficLight));
};var trafficLight = new TrafficLight();trafficLight.start();
// Output: Red Light - StoptrafficLight.start();
// Output: Green Light - GotrafficLight.start();
// Output: Yellow Light - Prepare to StoptrafficLight.start();
// Output: Red Light - Stop
  1. 空对象模式 (Null Object Pattern):
function Animal(name) {this.name = name;
}Animal.prototype.makeSound = function () {throw new Error("This method should be overridden");
};function Dog(name) {Animal.call(this, name);
}Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;Dog.prototype.makeSound = function () {console.log(this.name + " barks");
};function NullAnimal() {}NullAnimal.prototype.makeSound = function () {console.log("No sound");
};function AnimalFactory() {}AnimalFactory.prototype.createAnimal = function (name) {if (name === "dog") {return new Dog(name);} else {return new NullAnimal();}
};var animalFactory = new AnimalFactory();var animal1 = animalFactory.createAnimal("dog");
animal1.makeSound(); // Output: dog barksvar animal2 = animalFactory.createAnimal("cat");
animal2.makeSound(); // Output: No sound
  1. 模板方法模式 (Template Method Pattern):
function Beverage() {}Beverage.prototype.prepare = function () {this.boilWater();this.brew();this.pourInCup();this.addCondiments();
};Beverage.prototype.boilWater = function () {console.log("Boiling water");
};Beverage.prototype.pourInCup = function () {console.log("Pouring into cup");
};Beverage.prototype.brew = function () {throw new Error("This method should be overridden");
};Beverage.prototype.addCondiments = function () {throw new Error("This method should be overridden");
};function Coffee() {}Coffee.prototype = Object.create(Beverage.prototype);
Coffee.prototype.constructor = Coffee;Coffee.prototype.brew = function () {console.log("Brewing coffee");
};Coffee.prototype.addCondiments = function () {console.log("Adding sugar and milk");
};function Tea() {}Tea.prototype = Object.create(Beverage.prototype);
Tea.prototype.constructor = Tea;Tea.prototype.brew = function () {console.log("Steeping tea");
};Tea.prototype.addCondiments = function () {console.log("Adding lemon");
};var coffee = new Coffee();
coffee.prepare();
// Output:
// Boiling water
// Brewing coffee
// Pouring into cup
// Adding sugar and milkvar tea = new Tea();
tea.prepare();
// Output:
// Boiling water
// Steeping tea
// Pouring into cup
// Adding lemon

这是一些常见的设计模式的例子

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/20635.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Quartz使用文档,使用Quartz实现动态任务,Spring集成Quartz,Quartz集群部署,Quartz源码分析

文章目录 一、Quartz 基本介绍二、Quartz Java 编程1、文档2、引入依赖3、入门案例4、默认配置文件 三、Quartz 重要组件1、Quartz架构体系2、JobDetail3、Trigger&#xff08;1&#xff09;代码实例&#xff08;2&#xff09;SimpleTrigger&#xff08;3&#xff09;CalendarI…

python-Excel数据模型文档转为MySQL数据库建表语句(需要连接数据库)-工作小记

将指定Excel文档转为create table 建表语句。该脚本适用于单一且简单的建表语句 呈现效果 代码 # -*- coding:utf-8 -*- # Time : 2023/8/2 17:50 # Author: 水兵没月 # File : excel_2_mysql建表语句.py import reimport pandas as pd import mysql.connectordb 库名mydb m…

ELK高级搜索(一)

文章目录 ELK搜索1&#xff0e;简介1.1 内容1.2 面向 2&#xff0e;Elastic Stack2.1 简介2.2 特色2.3 组件介绍 3&#xff0e;Elasticsearch3.1 搜索是什么3.2 数据库搜索3.3 全文检索3.4 倒排索引3.5 Lucene3.6 Elasticsearch3.6.1 Elasticsearch的功能3.6.2 Elasticsearch使…

【算法题】2790. 长度递增组的最大数目

题目&#xff1a; 给你一个下标从 0 开始、长度为 n 的数组 usageLimits 。 你的任务是使用从 0 到 n - 1 的数字创建若干组&#xff0c;并确保每个数字 i 在 所有组 中使用的次数总共不超过 usageLimits[i] 次。此外&#xff0c;还必须满足以下条件&#xff1a; 每个组必须…

Python3 网络爬虫开发实战

JavaScript逆向爬虫 JavaScript接口加密技术&#xff0c;JavaScript有以下两个特点&#xff1a; JS代码运行在客户端&#xff0c;所以它必须在用户浏览器加载并运行JS代码公开透明&#xff0c;所以浏览器可以直接获取到正在运行的JS源码。 所以JS代码不安全&#xff0c;任何…

电脑安装新系统不知道去哪里下载,看我就够了

大家在日常生活中肯定都会遇到电脑安装系统的需求&#xff0c;如果去微软官方购买正版的系统又很贵&#xff0c;又不太想花这个冤枉钱&#xff0c;这个时候我们就不得不去网上查找一些免费好用的系统&#xff0c;可是百度一下&#xff0c;或者Google一下&#xff0c;各种下载系…

设计模式思考,简单工厂模式和策略模式的区别?

最近学习了设计模式&#xff0c;学到简单工厂模式和策略模式的时候想&#xff0c;这两个模式不是一样嘛&#xff0c;仔细思考之后发现大体设计思路是一样的&#xff0c;但是细节却有所不一样。 简单工厂模式 简单工厂模式是一种创建型设计模式&#xff0c;它主要涉及对象的创建…

Android性能优化—卡顿分析与布局优化

一、什么是卡顿&#xff1f;或者说我们怎么感知APP卡顿&#xff1f; 这里面涉及到android UI渲染机制&#xff0c;我们先了解一下android UI是怎么渲染的&#xff0c;android的View到底是如何一步一步显示到屏幕上的&#xff1f; android系统渲染页面流程&#xff1a; 1&…

短视频矩阵营销系统技术开发者开发笔记分享

一、开发短视频seo抖音矩阵系统需要遵循以下步骤&#xff1a; 1. 确定系统需求&#xff1a;根据客户的需求&#xff0c;确定系统的功能和特点&#xff0c;例如用户注册登录、视频上传、视频浏览、评论点赞等。 2. 设计系统架构&#xff1a;根据系统需求&#xff0c;设计系统的…

[STL]详解list模拟实现

[STL]list模拟实现 文章目录 [STL]list模拟实现1. 整体结构总览2. 成员变量解析3. 默认成员函数构造函数1迭代器区间构造函数拷贝构造函数赋值运算符重载析构函数 4. 迭代器及相关函数迭代器整体结构总览迭代器的模拟实现begin函数和end函数begin函数和end函数const版本 5. 数据…

Python 操作 MySQL 数据库

Python 操作 MySQL 数据库 Python 标准数据库接口为 Python DB-API&#xff0c;Python DB-API为开发人员提供了数据库应用编程接口。 Python 数据库接口支持非常多的数据库&#xff0c;你可以选择适合你项目的数据库&#xff1a; GadFlymSQLMySQLPostgreSQLMicrosoft SQL Se…

FreeIPA Server/Client不同版本组合,对podman rootless container的支持

FreeIPA Server/Client不同版本组合&#xff0c;对podman rootless container的支持 根据实验&#xff0c; CentOS 7.9 yum仓库自带的FreeIPA Server 4.6.8&#xff0c; ipa client版本支持CentOS 7.9 yum仓库自带的FreeIPA Client 4.6.8不支持subids&#xff0c;podman调用…

机器学习-Basic Concept

机器学习(Basic Concept) videopptblog Where does the error come from? 在前面我们讨论误差的时候&#xff0c;我们提到了Average Error On Testing Data是最重要的 A more complex model does not lead to better performance on test data Bias And Variance Bias(偏差) …

re学习(26)攻防世界-re-BABYRE(IDA无法分析出函数-代码混淆)

题目链接&#xff1a;https://adworld.xctf.org.cn/challenges/list elf是一种对可执行文件&#xff0c;目标文件和库使用的文件格式&#xff0c;跟window下的PE文件格式类似。载入IDA后如果需要对此文件进行远程调试&#xff0c;需要用linux系统&#xff0c;比如说Ubuntu&…

【机器学习】西瓜书学习心得及课后习题参考答案—第3章线性模型

过了一遍第三章&#xff0c;大致理解了内容&#xff0c;认识了线性回归模型&#xff0c;对数几率回归模型&#xff0c;线性判别分析方法&#xff0c;以及多分类学习&#xff0c;其中有很多数学推理过程以参考他人现有思想为主&#xff0c;没有亲手去推。 术语学习 线性模型 l…

排序八卦炉之冒泡、快排

文章目录 1.冒泡排序1.1代码实现1.2复杂度 2.快速排序2.1人物及思想介绍【源于百度】2.2hoare【霍尔】版本1.初识代码2.代码分析3.思其因果 3.相关博客 1.冒泡排序 1.1代码实现 //插入排序 O(N)~O(N^2) //冒泡排序 O(N)~O(N^2) //当数据有序 二者均为O(N) //当数据接近有序或…

【多模态】ALIGN——使用噪声文本数据进行视觉语言感知预训练

ALIGN: A Large-scale ImaGe and Noisy-text embedding 目录 &#x1f36d;&#x1f36d;1.网络介绍 &#x1f36d;&#x1f36d;2.大规模噪声图像文本数据集 &#x1f438;&#x1f438;2.1图像过滤器 &#x1f438;&#x1f438;2.2文本过滤器 &#x1f36d;&#x1f3…

Bean的实例化方法

目录 1.工厂模式通常有三种形态&#xff1a; 2.简单工厂 2.1 静态工厂 2.1通过factory-bean实例化 2.3通过FactoryBean接口实例化 3.测试 关于容器的使用 3.1获得spring文件方式 3.2getBean方式 4.关闭容器 1.工厂模式通常有三种&#xff1a; 第一种&#xff1a;简单工…

利用鸿鹄快速构建公司IT设备管理方案

需求描述 相信应该有一部分朋友跟我们一样&#xff0c;公司内部有很多各种各样的系统&#xff0c;比如资产管理、CRM、issue管理等等。这篇文章介绍下&#xff0c;鸿鹄是如何让我们的资产系统&#xff0c;按照我们的需求展示数据的。 我们的资产管理系统&#xff0c;是使用开源…

Go语音介绍

Go语言介绍 Go 即Golang&#xff0c;是Google公司2009年11月正式对外公开的一门编程语言。 Go是静态强类型语言&#xff0c;是区别于解析型语言的编译型语言。 解析型语言——源代码是先翻译为中间代码&#xff0c;然后由解析器对代码进行解释执行。 编译型语言——源代码编…