设计模式梳理
solid设计模式基本原则
SOLID 是面向对象设计中的五个基本原则,旨在提高代码的可维护性和可扩展性。以下是每个原则的简要说明:
单一职责原则(SRP):Single Responsibility Principle
每个类应该只有一个职责,即一个类应该只有一个引起变化的原因。
开放关闭原则(OCP):Open/Closed Principle
软件实体(类、模块、函数等)应该对扩展开放,对修改关闭。也就是说,可以通过添加新代码来扩展功能,而不是修改现有代码。
里氏替换原则(LSP):Liskov Substitution Principle
子类对象应该能够替换父类对象而不会影响程序的正确性。即,如果 S 是 T 的子类型,那么可以用 S 替换 T。
接口隔离原则(ISP):Interface Segregation Principle
不应该强迫客户依赖它们不使用的方法。即,应该将大接口拆分成多个小接口,以便客户只需要知道它们感兴趣的方法。
依赖倒转原则(DIP):Dependency Inversion Principle
高层模块不应该依赖于低层模块,二者都应该依赖于抽象。抽象不应该依赖于细节,细节应该依赖于抽象。
单例模式
const Singleton = (function () {
let instance;
function createInstance() {
const object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 使用
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
- 模块模式(Module)
const Module = (function () {
let privateVar = "I am private";
return {
publicMethod: function () {
console.log(privateVar);
}
};
})();
// 使用
Module.publicMethod(); // I am private
- 观察者模式(Observer)
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
notifyObservers(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
console.log(`Observer received data: ${data}`);
}
}
// 使用
const subject = new Subject();
const observer1 = new Observer();
subject.addObserver(observer1);
subject.notifyObservers("Hello!"); // Observer received data: Hello!
- 命令模式(Command)
class Command {
constructor(receiver) {
this.receiver = receiver;
}
execute() {
this.receiver.action();
}
}
class Receiver {
action() {
console.log("Receiver action executed");
}
}
// 使用
const receiver = new Receiver();
const command = new Command(receiver);
command.execute(); // Receiver action executed
- 策略模式(Strategy)
class Strategy {
constructor(strategy) {
this.strategy = strategy;
}
execute(a, b) {
return this.strategy(a, b);
}
}
// 策略函数
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
// 使用
const addStrategy = new Strategy(add);
console.log(addStrategy.execute(2, 3)); // 5
const multiplyStrategy = new Strategy(multiply);
console.log(multiplyStrategy.execute(2, 3)); // 6
- 代理模式(Proxy)
class RealSubject {
request() {
console.log("RealSubject: Handling request.");
}
}
class Proxy {
constructor(realSubject) {
this.realSubject = realSubject;
}
request() {
console.log("Proxy: Logging request.");
this.realSubject.request();
}
}
// 使用
const realSubject = new RealSubject();
const proxy = new Proxy(realSubject);
proxy.request(); // Proxy: Logging request. \n RealSubject: Handling request.
- 适配器模式(Adapter)
class OldSystem {
request() {
return "Old system response";
}
}
class NewSystem {
request() {
return "New system response";
}
}
class Adapter {
constructor(oldSystem) {
this.oldSystem = oldSystem;
}
request() {
return this.oldSystem.request();
}
}
// 使用
const oldSystem = new OldSystem();
const adapter = new Adapter(oldSystem);
console.log(adapter.request()); // Old system response
- 外观模式(Facade)
class SubsystemA {
operationA() {
return "Subsystem A operation";
}
}
class SubsystemB {
operationB() {
return "Subsystem B operation";
}
}
class Facade {
constructor() {
this.subsystemA = new SubsystemA();
this.subsystemB = new SubsystemB();
}
operation() {
return `${this.subsystemA.operationA()} and ${this.subsystemB.operationB()}`;
}
}
// 使用
const facade = new Facade();
console.log(facade.operation()); // Subsystem A operation and Subsystem B operation
- 组合模式(Composite)
class Component {
constructor(name) {
this.name = name;
}
operation() {
console.log(this.name);
}
}
class Composite extends Component {
constructor(name) {
super(name);
this.children = [];
}
add(child) {
this.children.push(child);
}
operation() {
super.operation();
this.children.forEach(child => child.operation());
}
}
// 使用
const leaf1 = new Component("Leaf 1");
const leaf2 = new Component("Leaf 2");
const composite = new Composite("Composite");
composite.add(leaf1);
composite.add(leaf2);
composite.operation();
// Composite
// Leaf 1
// Leaf 2
- 状态模式(State)
class Context {
constructor() {
this.state = null;
}
setState(state) {
this.state = state;
this.state.setContext(this);
}
request() {
this.state.handle();
}
}
class StateA {
setContext(context) {
this.context = context;
}
handle() {
console.log("State A handling request");
this.context.setState(new StateB());
}
}
class StateB {
setContext(context) {
this.context = context;
}
handle() {
console.log("State B handling request");
}
}
// 使用
const context = new Context();
context.setState(new StateA());
context.request(); // State A handling request
context.request(); // State B handling request

浙公网安备 33010602011771号