JavaScript设计模式详解 🏗️
今天,让我们深入探讨JavaScript中的设计模式。设计模式是软件开发中的最佳实践,它们可以帮助我们写出更加可维护和可扩展的代码。
设计模式基础 🌟
💡 小知识:设计模式是软件开发中常见问题的典型解决方案。它们不是具体的代码片段,而是解决特定问题的通用模板。
创建型模式 🏭
javascript
// 1. 单例模式
class Singleton {
private static instance: Singleton;
private constructor() {}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
// 2. 工厂模式
class ProductFactory {
static createProduct(type) {
switch (type) {
case 'A':
return new ProductA();
case 'B':
return new ProductB();
default:
throw new Error('Unknown product type');
}
}
}
// 3. 建造者模式
class ProductBuilder {
constructor() {
this.reset();
}
reset() {
this.product = new Product();
}
setName(name) {
this.product.name = name;
return this;
}
setPrice(price) {
this.product.price = price;
return this;
}
setFeatures(features) {
this.product.features = features;
return this;
}
build() {
const result = this.product;
this.reset();
return result;
}
}
// 4. 原型模式
class Prototype {
clone() {
const clone = Object.create(this);
clone.initialize(this);
return clone;
}
initialize(source) {
// 深拷贝源对象的属性
}
}
结构型模式 🔨
javascript
// 1. 适配器模式
class OldAPI {
specificRequest() {
return 'Old API response';
}
}
class NewAPI {
request() {
const oldAPI = new OldAPI();
return `Adapted: ${oldAPI.specificRequest()}`;
}
}
// 2. 装饰器模式
class Component {
operation() {
return 'Basic operation';
}
}
class Decorator {
constructor(component) {
this.component = component;
}
operation() {
return `Decorated: ${this.component.operation()}`;
}
}
// 3. 代理模式
class RealSubject {
request() {
return 'Real subject response';
}
}
class Proxy {
constructor() {
this.realSubject = null;
}
request() {
if (!this.realSubject) {
this.realSubject = new RealSubject();
}
return `Proxy: ${this.realSubject.request()}`;
}
}
// 4. 外观模式
class Facade {
constructor() {
this.subsystem1 = new Subsystem1();
this.subsystem2 = new Subsystem2();
}
operation() {
return `Facade combines: ${this.subsystem1.operation1()} and ${this.subsystem2.operation2()}`;
}
}
行为型模式 🎭
javascript
// 1. 观察者模式
class Subject {
constructor() {
this.observers = new Set();
}
attach(observer) {
this.observers.add(observer);
}
detach(observer) {
this.observers.delete(observer);
}
notify(data) {
for (const observer of this.observers) {
observer.update(data);
}
}
}
class Observer {
update(data) {
console.log('Received update:', data);
}
}
// 2. 策略模式
class Context {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
executeStrategy(data) {
return this.strategy.execute(data);
}
}
class Strategy {
execute(data) {
// 具体策略实现
}
}
// 3. 命令模式
class Command {
constructor(receiver) {
this.receiver = receiver;
}
execute() {
this.receiver.action();
}
}
class Receiver {
action() {
console.log('Receiver performs action');
}
}
class Invoker {
constructor() {
this.commands = [];
}
addCommand(command) {
this.commands.push(command);
}
executeCommands() {
this.commands.forEach(command => command.execute());
this.commands = [];
}
}
// 4. 状态模式
class Context {
constructor(state) {
this.state = state;
}
setState(state) {
this.state = state;
}
request() {
this.state.handle(this);
}
}
class State {
handle(context) {
// 具体状态处理逻辑
}
}
实际应用示例 💼
javascript
// 1. 表单验证器
class FormValidator {
constructor() {
this.rules = new Map();
this.errors = new Map();
}
addRule(field, ...validations) {
this.rules.set(field, validations);
}
validate(data) {
this.errors.clear();
for (const [field, rules] of this.rules) {
const value = data[field];
const fieldErrors = rules
.map(rule => rule(value))
.filter(error => error !== null);
if (fieldErrors.length > 0) {
this.errors.set(field, fieldErrors);
}
}
return this.errors.size === 0;
}
getErrors() {
return Object.fromEntries(this.errors);
}
}
// 2. 数据存储管理器
class StorageManager {
private static instance: StorageManager;
private storage: Map<string, any>;
private constructor() {
this.storage = new Map();
}
static getInstance() {
if (!StorageManager.instance) {
StorageManager.instance = new StorageManager();
}
return StorageManager.instance;
}
set(key: string, value: any) {
this.storage.set(key, value);
}
get(key: string) {
return this.storage.get(key);
}
remove(key: string) {
this.storage.delete(key);
}
clear() {
this.storage.clear();
}
}
// 3. UI组件工厂
class UIFactory {
static createButton(config) {
const button = document.createElement('button');
button.textContent = config.text;
button.className = config.className;
if (config.onClick) {
button.addEventListener('click', config.onClick);
}
return button;
}
static createInput(config) {
const input = document.createElement('input');
input.type = config.type || 'text';
input.placeholder = config.placeholder;
input.className = config.className;
if (config.onChange) {
input.addEventListener('change', config.onChange);
}
return input;
}
static createSelect(config) {
const select = document.createElement('select');
select.className = config.className;
config.options.forEach(option => {
const optionElement = document.createElement('option');
optionElement.value = option.value;
optionElement.textContent = option.text;
select.appendChild(optionElement);
});
if (config.onChange) {
select.addEventListener('change', config.onChange);
}
return select;
}
}
性能优化考虑 ⚡
javascript
// 1. 对象池模式
class ObjectPool {
constructor(createFn, initialSize = 5) {
this.createFn = createFn;
this.pool = [];
// 预创建对象
for (let i = 0; i < initialSize; i++) {
this.pool.push(this.createFn());
}
}
acquire() {
return this.pool.length > 0
? this.pool.pop()
: this.createFn();
}
release(obj) {
if (obj.reset) {
obj.reset();
}
this.pool.push(obj);
}
}
// 2. 享元模式
class FlyweightFactory {
constructor() {
this.flyweights = new Map();
}
getFlyweight(key) {
if (!this.flyweights.has(key)) {
this.flyweights.set(key, new Flyweight(key));
}
return this.flyweights.get(key);
}
}
// 3. 延迟加载模式
class LazyLoader {
constructor() {
this.instances = new Map();
this.factories = new Map();
}
register(key, factory) {
this.factories.set(key, factory);
}
get(key) {
if (!this.instances.has(key)) {
const factory = this.factories.get(key);
if (factory) {
this.instances.set(key, factory());
}
}
return this.instances.get(key);
}
}
最佳实践建议 💡
- 模式选择原则
javascript
// 1. 根据场景选择合适的模式
function patternSelection() {
// 单例模式:全局状态管理
const globalState = Singleton.getInstance();
// 工厂模式:对象创建
const product = ProductFactory.createProduct('A');
// 观察者模式:事件处理
const eventSystem = new Subject();
}
// 2. 避免过度设计
function avoidOverEngineering() {
// 不好的做法:简单问题复杂化
class ComplexSolution {
// 过度使用设计模式
}
// 好的做法:保持简单
function simpleSolution() {
// 直接解决问题
}
}
// 3. 模式组合使用
function patternCombination() {
// 组合使用多个模式
class ModernApplication {
constructor() {
this.state = Singleton.getInstance();
this.eventSystem = new Subject();
this.uiFactory = new UIFactory();
}
}
}
结语 📝
设计模式是编写高质量JavaScript代码的重要工具。我们学习了:
- 创建型模式的实现和应用
- 结构型模式的使用场景
- 行为型模式的具体示例
- 实际应用中的模式运用
- 性能优化和最佳实践
💡 学习建议:在使用设计模式时,要根据具体场景选择合适的模式,避免过度设计。同时,要理解每种模式的优缺点,在实际应用中灵活运用。
如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇
终身学习,共同成长。
咱们下一期见
💻