JavaScript 前端最常用的设计模式(实际案例)
大家好,在这篇文章中,我想向大家展示如何在项目中轻松地实现一些常见的设计模式。这些模式有助于我们编写可维护、灵活且易读的代码。当需要添加更多功能而无需对代码进行大量修改时,您将会体会到它们的优势。
现在,让我们开始编写代码吧!💻
1. 模块化模式。
模块模式是 JavaScript 世界中最常见的模式之一,它对于将函数和变量的逻辑封装在同一作用域中并管理它们的访问权限非常有用,类似于访问修饰符(public、private 等)。
网上有很多不同变体的例子,但我尽量创建了一个尽可能简单的示例。
注意:我们可以在ES6 的import /export语法中看到这种模式。
复杂度: ⚡
var module = (function () {
let options = {color:"red"}
/*
private code here
*/
const setSize = function () {
options["size"] = 12;
};
/*
public code here
*/
return {
getOptions: function () {
setSize();
return options;
}
};
})();
module.getOptions();
2.战略模式。
当我们需要处理类似任务并在运行时进行任务切换时,策略设计模式非常实用。
这种模式可以帮助我们减少大量的 if-else 语句,其原理很简单:将任务封装成小块,并使用对象字面量来访问具体的策略。
这种模式在 JavaScript 中实现起来非常简单,因为它不需要接口或任何复杂的实现。
使用场景:假设我们有一个下拉菜单,其中包含不同的用户类型(普通用户、管理员和访客),我们希望根据所选的用户类型在同一页面上显示不同的表单。
这里以React为例,但你也可以将其应用于其他 JS 框架。
复杂度: ⚡⚡
// React components section
import React from "react";
import UserForm from "./userForm";
import AdminForm from "./adminForm";
import GuestForm from "./guestForm";
/*
* This object literal will help to encapsulate all the forms that could we have.
*/
const FormsManage = {
user : {
render(props){
return <UserForm {...props} />
}
},
admin:{
render(props){
return <AdminForm {...props} />
}
},
guest:{
render(props) {
return <GuestForm {...props}/>
}
}
};
/*
* Main form component
*/
const Form = (props) => {
// here we are getting the form by type
const userForm = FormsManage[props.type];
return userForm.render(props);
};
export default Form;
3. 构建者模式。
当我们需要创建具有不同变体的复杂对象,并且希望能够灵活地修改构建过程而不影响对象自身的表示时,可以使用建造者模式。
我尝试创建一个可以在实际应用中使用的示例。
使用场景:我们需要将 API 数据转换为第三方组件能够理解的格式多少次?对于这种情况,我们可以使用构建器模式来创建组件需要的对象,并将构造逻辑分离出来。
复杂度: ⚡⚡⚡
/*
* Mock class
*/
class DataTable{
constructor(data ,options){
this.data = data;
this.options = options
}
getData(){
return this.data;
}
}
/*
* Builder class to create DataTable objects.
*/
function DataTableBuilder () {
let defualtOptions ={ width:100, height:200, headerFixed: false };
/*
* Method to make the format required.
*/
function generateFormattedData(data,header){
return data.map(item => {
let result = {};
item.forEach((val,idx) => {
result[header[idx] || "df"+idx] = val;
});
return result;
});
};
/*
* Public steps methods
*/
return {
addHeader(header){
this.header = header || [];
return this;
},
addData(data){
this.data = data || [];
return this;
},
addOptions(options){
this.options = { ...defualtOptions, ...options};
return this;
},
build(){
const formattedData = generateFormattedData(this.data,this.header);
return new DataTable(formattedData,this.options);
}
}
};
/*
* Data needed to build the Datatable object
*/
const header=["name","age","position"];
const rows = [["Luis",19,"Dev"],["Bob",23,"HR"], ["Michel",25,"Accounter"]];
const options = { headerFixed:true };
/*
* Start to the builder process
*/
const dt = new DataTableBuilder()
.addHeader(header)
.addData(rows)
.addOptions(options)
.build();
dt.getData();
结论。
软件开发领域存在许多设计模式,它们各有特点,但作为开发人员,我们的工作是理解和分析哪些模式能为我们的项目增加真正的价值,而不是带来更多的问题或复杂性。
如果你有一些对你有用的设计模式,请在讨论区分享;或者如果你想实现前面提到的某个模式但需要帮助,请告诉我,我可以帮忙。😉
文章来源:https://dev.to/lukocastillo/most-common-design-patterns-for-front-end-with-javascript-real-world-examples-2hj3
