一、设计模式介绍
设计模式是解决特定类型问题的通用方案,它们帮助开发者在设计和实现系统时提高代码的可复用性、可维护性和可扩展性。
二、常用的设计模式有哪些?
-
策略模式
-
工厂模式
-
单例模式
-
代理模式
-
工厂方法模式
-
观察者模式
-
模板方法模式
-
适配器模式
下面是一些常用的设计模式,每个设计模式的解析和实现模板:
1. 单例模式 (Singleton Pattern)
解析
单例模式确保一个类只有一个实例,并提供一个全局访问点。
实现模板(JavaScript)
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
}
// 其他方法和属性
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // 输出: true
实现模板(Java)
public class Singleton {
private static Singleton instance;
private Singleton() {
// 私有构造函数
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 工厂方法模式 (Factory Method Pattern)
解析
工厂方法模式定义一个创建对象的接口,但由子类决定实例化哪个类。
实现模板(JavaScript)
class Product {
use() {
throw new Error('You have to implement the method use!');
}
}
class ConcreteProductA extends Product {
use() {
console.log('Use product A');
}
}
class ConcreteProductB extends Product {
use() {
console.log('Use product B');
}
}
class Creator {
factoryMethod() {
// 子类会重写这个方法
throw new Error('You have to implement the method factoryMethod!');
}
someOperation() {
const product = this.factoryMethod();
product.use();
}
}
class ConcreteCreatorA extends Creator {
factoryMethod() {
return new ConcreteProductA();
}
}
class ConcreteCreatorB extends Creator {
factoryMe