设计模式在开发社区中一直是一个有争议的话题。有些工程师认为设计模式过于复杂,有些则有条不紊的使用着设计模式。作为一个 JavaScript 工程师,你的职业生涯中或多会接触到一些设计模式。让我们一起探讨 JavaScript 的几个常用的设计模式,并且体会设计模式能如何让你的代码看上去更感觉,更容易维护。
什么是设计模式
在软件开发过程中,设计模式是一种解决特定场景的通用方案。并不能直接转换成代码使用,它是一个描述或者模版,告诉我们该如何组织一类代码的实现。
维基百科中的描述: 在软件工程中,设计模式(design pattern)是对软件设计中普遍存在(反复出现)的各种问题,所提出的解决方案。
JavaScript 设计模式的类型
创造型(Creational):通过控制对象的创建模式,降低复杂性。
结构型(Structural):简化实现实体之间的关系。
行为型(Behavioral):关于对象之间如何通讯,提高灵活性。
🏭 工厂模式(Creational)
定义一个可以创建一个对象的 Creator(工厂) 抽象类,让子类实现 createFactory 决定创建一个什么对象,通常子类提供对 operateSometins 的实现。
abstract class Creator {
public abstract createFactory(): Product;
public operatSomething(): string {
const product = this.createFactory();
return product.operation();
}
}
class CarCreator extends Creator {
public createFactory(): Product {
return new CarProduct();
}
}
interface Product {
operation(): string
}
class CarProduct implements Product {
operation(): string {
return "create a new car";
}
}
class ShoeProduct implements Product {
operation(): string {
return "create a new shoe";
}
}
function clientCode(productor: Product) {
console.log(productor.operation())
}
clientCode(new CarProduct());
clientCode(new ShoeProduct());
reference:
https://www.thisdot.co/blog/clean-up-your-code-with-design-patterns-in-javascript
https://blog.openreplay.com/3-react-component-design-patterns-you-should-know-about