设计模式在开发社区中一直是一个有争议的话题。有些工程师认为设计模式过于复杂,有些则有条不紊的使用着设计模式。作为一个 JavaScript 工程师,你的职业生涯中或多会接触到一些设计模式。让我们一起探讨 JavaScript 的几个常用的设计模式,并且体会设计模式能如何让你的代码看上去更感觉,更容易维护。

什么是设计模式

在软件开发过程中,设计模式是一种解决特定场景的通用方案。并不能直接转换成代码使用,它是一个描述或者模版,告诉我们该如何组织一类代码的实现。
维基百科中的描述: 在软件工程中,设计模式(design pattern)是对软件设计中普遍存在(反复出现)的各种问题,所提出的解决方案。

JavaScript 设计模式的类型

创造型(Creational):通过控制对象的创建模式,降低复杂性。
结构型(Structural):简化实现实体之间的关系。
行为型(Behavioral):关于对象之间如何通讯,提高灵活性。

🏭 工厂模式(Creational)

定义一个可以创建一个对象的 Creator(工厂) 抽象类,让子类实现 createFactory 决定创建一个什么对象,通常子类提供对 operateSometins 的实现。

image.png

  1. abstract class Creator {
  2. public abstract createFactory(): Product;
  3. public operatSomething(): string {
  4. const product = this.createFactory();
  5. return product.operation();
  6. }
  7. }
  8. class CarCreator extends Creator {
  9. public createFactory(): Product {
  10. return new CarProduct();
  11. }
  12. }
  13. interface Product {
  14. operation(): string
  15. }
  16. class CarProduct implements Product {
  17. operation(): string {
  18. return "create a new car";
  19. }
  20. }
  21. class ShoeProduct implements Product {
  22. operation(): string {
  23. return "create a new shoe";
  24. }
  25. }
  26. function clientCode(productor: Product) {
  27. console.log(productor.operation())
  28. }
  29. clientCode(new CarProduct());
  30. 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