欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 【设计模式】01- 一文理解常用设计模式-“创建型模式”篇

【设计模式】01- 一文理解常用设计模式-“创建型模式”篇

2025/2/22 2:25:10 来源:https://blog.csdn.net/orbit4/article/details/145601038  浏览:    关键词:【设计模式】01- 一文理解常用设计模式-“创建型模式”篇

一、前言

最近在复习设计模式,撰写、整理了内容和代码片段,和大家一起交流学习。

设计模式是软件设计中常见问题的典型解决方案。

二、模式分类

模式可以根据其意图或目的来分类。常见的设计模式包括:

  • 创建型模式提供创建对象的机制, 增加已有代码的灵活性和可复用性;

  • 结构型模式介绍如何将对象和类组装成较大的结构, 并同时保持结构的灵活和高效;

  • 行为型模式负责对象间的高效沟通和职责委派;

本篇文章介绍创建型模式,后续会更新其他两类设计模式。


三、创建型模式概述

创建型模式主要用于对象的创建过程,它隐藏了对象的创建逻辑,使得代码更具灵活性和可维护性。

四、常见创建型模式(配合代码)

1、单例模式(Singleton Pattern)

确保一个类只有一个实例,并提供一个全局访问点来访问这个实例。

// 单例模式示例
const Singleton = (function () {let instance;function createInstance() {const object = new Object({ name: 'Singleton Object' });return object;}return {getInstance: function () {if (!instance) {instance = createInstance();}return instance;}};}());// 使用示例const instance1 = Singleton.getInstance();const instance2 = Singleton.getInstance();console.log(instance1 === instance2); // 输出: true

代码运行结果

2、工厂模式(Factory Pattern)

定义一个创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。

解释:工厂模式就像一个工厂,根据不同的需求生产不同的产品。你只需要告诉工厂你需要什么,工厂就会帮你创建出来。

// 工厂模式示例
function CarFactory() {this.createCar = function (type) {let car;if (type === 'sedan') {car = new Sedan();} else if (type === 'suv') {car = new SUV();}car.drive = function () {console.log(`Driving a ${this.constructor.name}`);};return car;};
}
​
function Sedan() {this.type = 'Sedan';
}
​
function SUV() {this.type = 'SUV';
}
​
// 使用示例
const factory = new CarFactory();
const sedan = factory.createCar('sedan');
const suv = factory.createCar('suv');
​
sedan.drive(); // 输出: Driving a Sedan
suv.drive();   // 输出: Driving a SUV

代码运行结果

3、抽象工厂模式(Abstract Factory Pattern)

提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

简单理解:就像一个超级工厂,能生产不同品牌的汽车系列产品。

// 抽象工厂模式示例
// 抽象工厂
function AbstractCarFactory() {this.createEngine = function () {throw new Error('This method must be overridden!');};this.createWheel = function () {throw new Error('This method must be overridden!');};
}
​
// 具体工厂:丰田工厂
function ToyotaFactory() {AbstractCarFactory.call(this);this.createEngine = function () {return new ToyotaEngine();};this.createWheel = function () {return new ToyotaWheel();};
}
​
// 具体工厂:本田工厂
function HondaFactory() {AbstractCarFactory.call(this);this.createEngine = function () {return new HondaEngine();};this.createWheel = function () {return new HondaWheel();};
}
​
// 丰田发动机
function ToyotaEngine() {this.start = function () {console.log('Toyota engine started');};
}
​
// 丰田车轮
function ToyotaWheel() {this.rotate = function () {console.log('Toyota wheel rotating');};
}
// 本田发动机
function HondaEngine() {this.start = function () {console.log('Honda engine started');};
}
​
// 本田车轮
function HondaWheel() {this.rotate = function () {console.log('Honda wheel rotating');};
}
​
// 使用示例
const toyotaFactory = new ToyotaFactory();
const toyotaEngine = toyotaFactory.createEngine();
const toyotaWheel = toyotaFactory.createWheel();
​
toyotaEngine.start(); // 输出: Toyota engine started
toyotaWheel.rotate(); // 输出: Toyota wheel rotating
​
const hondaFactory = new HondaFactory();
const hondaEngine = hondaFactory.createEngine();
const hondaWheel = hondaFactory.createWheel();
​
hondaEngine.start(); // 输出: Honda engine started
hondaWheel.rotate(); // 输出: Honda wheel rotating
代码运行结果

4、建造者模式(Builder Pattern)

将一个复杂对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。

简单理解:就像建造房子,有不同的建造步骤,最终可以建成不同风格的房子。

// 建造者模式示例
// 产品类:汽车
function Car() {this.wheels = null;this.engine = null;this.color = null;
​this.showInfo = function () {console.log(`Car with ${this.wheels} wheels, ${this.engine} engine and ${this.color} color`);};
}
​
// 建造者类
function CarBuilder() {this.car = new Car();
​this.setWheels = function (wheels) {this.car.wheels = wheels;return this;};
​this.setEngine = function (engine) {this.car.engine = engine;return this;};
​this.setColor = function (color) {this.car.color = color;return this;};
​this.build = function () {return this.car;};
}
​
// 使用示例
const builder = new CarBuilder();
const car = builder.setWheels(4).setEngine('V8').setColor('Red').build();
​
car.showInfo(); // 输出: Car with 4 wheels, V8 engine and Red color

代码运行结果

 

5、原型模式(Prototype Pattern)

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

简单理解:就像复印文件,有一个原始文件作为模板,然后可以复印出很多份一样的文件。

// 原型模式示例
const carPrototype = {brand: 'Unknown',model: 'Unknown',start: function () {console.log(`Starting the ${this.brand} ${this.model}`);},clone: function () {const clone = Object.create(this);return clone;}
};
​
// 使用示例
const car1 = carPrototype.clone();
car1.brand = 'Toyota';
car1.model = 'Corolla';
​
const car2 = carPrototype.clone();
car2.brand = 'Honda';
car2.model = 'Civic';
​
car1.start(); // 输出: Starting the Toyota Corolla
car2.start(); // 输出: Starting the Honda Civic

代码运行结果


五、小结

设计模式在编程当中还是挺重要的,优点包括但不限于:代码复用性更高、可维护性更强、可扩展性更好。

有时间可以花点时间学习/复习一下,相信对我们的编程技术和编程思维会有很多进步~

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词