工厂模式
工厂函数通常是指一个函数,它用来创建和返回其他函数或对象的实例。
人话: 当new Class 或 Function 时,根据传入的参数,而返回不同的值,这就是工厂模式。 (所以可以说,这是我们开发中,无意中用了最多的模式)
// 工厂模式示例:创建不同类型的图表组件// 创建柱状图组件
class BarChart {// ...
}// 创建折线图组件
class LineChart {// ...
}// 图表工厂类
class ChartFactory {createChart(type) {switch (type) {case 'bar':return new BarChart();case 'line':return new LineChart();// 可以添加更多的图表类型...default:throw new Error('Unsupported chart type');}}
}const chartFactory = new ChartFactory();
const barChart = chartFactory.createChart('bar');
const lineChart = chartFactory.createChart('line');
单例模式
// 单例模式示例:全局应用配置
class AppConfig {constructor() {this.config = {apiEndpoint: 'https://api.example.com',apiKey: 'your-api-key',// 其他配置项...};}getConfig() {return this.config;}
}const appConfig = new AppConfig();
export default appConfig;--------------------------------------
import appConfig from './appConfig.js';function fetchData() {const config = appConfig.getConfig();const apiEndpoint = config.apiEndpoint;const apiKey = config.apiKey;// 使用配置进行数据获取...
}