• 单一职责原则(Single Responsibility Principle)
  • 开闭原则(Open Closed Principle)
  • 里式替换原则(Liskov substitution principle)
  • 接口隔离原则(Interface segregation principle)
  • 依赖反转原则(Dependency inversion principle)

    单一职责原则(SRP)

    “A class or module should have a single responsibility”
    如何判断类的职责是否足够单一:

  • 类中的代码行数、函数或者属性过多

  • 类依赖的其他类过多,或者依赖类的其他类过多
  • 私有方法过多
  • 比较难给类起一个合适的名字
  • 类中大量的方法都是集中操作类中的某几个属性

    对扩展开放、修改关闭(OCP)

    “software entities (modules, classes, functions, etc.) should be open for extension, but closed for modification”
    the core idea of the above principle is that we should be able to add new functionalities without changing the existing code.

    开闭原则讲的就是代码的扩展性问题

  1. class Rectangle {
  2. public width: number;
  3. public height: number;
  4. constructor(width: number, height: number) {
  5. this.width = width;
  6. this.height = height;
  7. }
  8. }
  9. class Circle {
  10. public radius: number;
  11. constructor(radius: number) {
  12. this.radius = radius;
  13. }
  14. }
  15. function calculateAreasOfMultipleShapes(
  16. shapes: Array<Rectangle | Circle>
  17. ) {
  18. return shapes.reduce(
  19. (calculatedArea, shape) => {
  20. if (shape instanceof Rectangle) {
  21. return calculatedArea + shape.width * shape.height;
  22. }
  23. if (shape instanceof Circle) {
  24. return calculatedArea + shape.radius * Math.PI;
  25. }
  26. },
  27. 0
  28. );
  29. }

符合 开闭原则 的代码

  1. interface Shape {
  2. getArea(): number;
  3. }
  4. class Rectangle implements Shape {
  5. public width: number;
  6. public height: number;
  7. constructor(width: number, height: number) {
  8. this.width = width;
  9. this.height = height;
  10. }
  11. public getArea() {
  12. return this.width * this.height;
  13. }
  14. }
  15. class Circle implements Shape {
  16. public radius: number;
  17. constructor(radius: number) {
  18. this.radius = radius;
  19. }
  20. public getArea() {
  21. return this.radius * Math.PI;
  22. }
  23. }
  24. function calculateAreasOfMultipleShapes(
  25. shapes: Shape[]
  26. ) {
  27. return shapes.reduce(
  28. (calculatedArea, shape) => {
  29. return calculatedArea + shape.getArea();
  30. },
  31. 0
  32. );
  33. }

里式替换(LSP)

Replacing an instance of a class with its child class should not produce any negative side effects

  1. 子类可以替换父类的位置,并且不影响程序
  2. 父类有的功能子类都有,但是子类可以在子类的基础上,添加功能

设计原则:

  • Methods of a subclass that override methods of a base class must have exactly the same number of arguments
  • Each argument of the override method must be the same type as the method of the base class
  • The return type of the overridden method must be the same as the method of the base class
  • The types of exceptions thrown from the overridden method must be the same as the method of the base class

    接口隔离原则(ISP)

  • 把接口理解为一组 API 接口集合

    • 如果部分接口只被部分调用者使用,需要将这部分接口隔离出来,给其单独使用
  • 把接口理解为单个 API 接口或函数
    • 函数的设计功能单一,不要将多个不同的功能逻辑在一个函数中实现
  • 把接口理解为 OOP 中的接口概念 ```typescript interface Vehicle { make: string; numberOfWheels: number; maxSpeed?: number; getReachKm(fuel: number, kmPerLitre: number): number; }

class Car implements Vehicle { make: string; numberOfWheels: number; maxSpeed: number;

constructor(make, numberOfWheels, maxSpeed) { this.make = make; this.numberOfWheels = numberOfWheels; this.maxSpeed = maxSpeed; }

getReachKm(fuel: number, kmPerLitre: number) { return fuel * kmPerLitre; } }

const carObj = new Car(“BMW”, 4, 240);

  1. <a name="syjtV"></a>
  2. # 依赖反转(DIP)
  3. 1. 高层次的模块不应该依赖于低层次的模块,两者都应该依赖于抽象接口
  4. 1. 抽象接口不应该依赖于具体实现,而具体实现则应该依赖于抽象接口
  5. > Whenever a module relies on an abstraction(interface or abstract class) as dependency, that dependency can be swapped for another implementation, like a plugin. Therefore, decoupling the module from its dependency.
  6. 通过依赖反转,使得模块可以插件化加载。<br />![WX20210513-102811@2x.png](https://cdn.nlark.com/yuque/0/2021/png/651859/1620872928416-20fa2b7a-efdc-4968-a787-23987d6c6022.png#clientId=u31c13530-38e6-4&from=ui&id=u4ed73e11&margin=%5Bobject%20Object%5D&name=WX20210513-102811%402x.png&originHeight=878&originWidth=1504&originalType=binary&size=86787&status=done&style=none&taskId=ufb5cbc80-5b03-4b4c-8a70-251f88f5b51)
  7. ```typescript
  8. // domain/ApiClient.ts
  9. export interface ApiClient {
  10. createUser: (user: User) => Promise<void>;
  11. getUserByEmail: (email: string) => Promise<User>;
  12. // ...
  13. }
  1. // infra/HttpClient.ts
  2. import axios from "axios";
  3. import ApiClient from "domain/ApiClient";
  4. export function HttpClient(): ApiClient {
  5. return {
  6. createUser: async (user: User) => {
  7. return axios.post(/* ... */);
  8. },
  9. getUserByEmail: async (email: string) => {
  10. return axios.get(/* ... */);
  11. },
  12. };
  13. }
  1. // domain/SignupService.ts
  2. import ApiClient from "domain/ApiClient"; // ✅ the domain depends on an abstraction of the infra
  3. export function SignupService(client: ApiClient) {
  4. return async (email: string, password: string) => {
  5. const existingUser = await client.getUserByEmail(email);
  6. if (existingUser) {
  7. throw new Error("Email already used");
  8. }
  9. return client.createUser({ email, password });
  10. };
  11. }
  1. // index.ts
  2. import SignupService from "domain/signup";
  3. import HttpClient from "infra/HttpClient";
  4. const signup = SignupService(HttpClient());
  5. signup("bob@bob.com", "pwd123");

参考资料

  1. 15 | 理论一:对于单一职责原则,如何判定某个类的职责是否够“单一”?
  2. applying solid principles to your typescript code
  3. Liskov Substitution Principle in JavaScript and TypeScript
  4. SOLID: Interface Segregation Principle in JavaScript and TypeScript
  5. Dependency Inversion Principle in Functional TypeScript