J03.5 质量 qualité

SOLID


  • 单一职责原则(SRP: Single Responsibility Principle)
  • 开闭原则(OCP: Open/Closed Principle)
  • 里氏替换原则(LSP: Liskov Substitution Principle)
  • 接口隔离原则(ISP: Interface Segregation Principle)
  • 依赖反转原则(DIP: Dependency Inversion Principle)

SRP:单一职责原则

  • 一个类(一个函数、一个方法)应该只承担一个职责。
  • 每个职责的变更会引发类的修改(规范的变动)。
  • 一个承担多重职责的类会导致职责之间的耦合。

OCP:开闭原则(Open/Closed Principle)

  • 一个模块(类、包)应对扩展开放,对修改关闭:
    • 对扩展开放:模块可以通过新行为扩展。
    • 对修改关闭:这些扩展不需要修改已有代码。
  • 使用面向对象机制:组合、继承、抽象类、接口等。
  • 根据以下需求识别开闭点:
    • 客户的可扩展性需求。
    • 开发者的灵活性需求。

LSP:里氏替换原则(Liskov Substitution Principle)

  • 如果 S 是 T 的子类型,则 T 类型的对象可以被 S 类型的对象替换,而不会破坏程序的正确性。
  • 该原则可能与继承作为代码复用的使用方式相冲突:子类必须保持可替换性。
  • 按契约设计:在子类中重新定义方法时,可以弱化前置条件,但必须保留或增强后置条件。

ISP:接口隔离原则(Interface Segregation Principle)

  • 客户端不应被迫依赖它不使用的接口。
  • 每个客户端只应“看到”它实际使用的服务。
  • 避免的常见错误:将一组服务积累到一个类中,导致不必要的依赖。
  • 解决方案:为不同类型的客户端设计独立的接口

DIP:依赖反转原则(Dependency Inversion Principle)

  • 高层模块(业务逻辑)不应依赖于低层模块(细节),两者都应依赖于抽象。
  • 抽象不应依赖于细节;细节应该依赖于抽象。
  • 低层模块更容易因执行环境的变化而修改。
  • 高层模块(业务逻辑)应依赖抽象(接口),以建模所需的服务。

STUPID


  • Singleton(单例模式的滥用)。
  • Tight coupling(强耦合)。
  • Untestability(不可测试)。
  • Premature optimization(过早优化)。
  • Indescriptive naming(缺乏描述性的命名)。
  • Duplication(代码重复)。

DRY, KISS, YAGNI


  • DRY: Don't Repeat Yourself(不要重复自己)。
  • KISS: Keep It Simple Stupid(保持简单,傻瓜化)。
  • YAGNI: You Aren’t Gonna Need It(你不会需要它)。

LoD:迪米特法则(Law of Demeter)


  • 原则:只与直接的邻居通信。
  • 允许发送消息给:
    • 自身(this)。
    • 被存储为属性的对象。
    • 方法的参数对象。
    • 方法创建的对象。
    • 全局对象(如单例)。

模型-视图-控制器 (MVC)


  • 模型 (Model):负责数据的管理和更新。
  • 视图 (View):负责数据的展示。
  • 控制器 (Controller):负责用户交互和业务逻辑。
  • 关系图:
    • 用户的操作通过控制器影响数据的更新,同时通知视图进行刷新。

设计模式


  1. 定义
    • 设计模式是通用问题的通用解决方案。
    • 提供了灵活和可重用的设计。
  2. 分类
    • 创建型模式:工厂方法、抽象工厂、建造者、原型、单例。
    • 结构型模式:适配器、桥接、组合、装饰器、外观、享元、代理。
    • 行为型模式:观察者、迭代器、命令、责任链、状态、策略、模板方法等。
  3. 重要模式介绍
    • 组合模式:支持对象树结构,允许将对象组视为单个对象。
    • 装饰器模式:动态修改对象行为,比继承更灵活。
    • 原型模式:通过克隆现有对象创建新对象。
    • 单例模式:确保类的唯一实例并提供全局访问点。

创建型模式


创建型模式主要解决对象实例化的灵活性问题,提供创建对象的通用解决方案,确保代码对对象类型的依赖降低,同时提高扩展性。以下是五种常用的创建型模式:

  1. 工厂方法模式(Factory Method)
    • 定义:定义一个创建对象的接口,但由子类决定实例化哪一个类。

    • 特点:使用工厂方法代替直接实例化,使代码对具体类解耦。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      // 抽象产品
      public interface Product {
      void use();
      }

      // 具体产品
      public class ConcreteProductA implements Product {
      public void use() { System.out.println("Using Product A"); }
      }

      public class ConcreteProductB implements Product {
      public void use() { System.out.println("Using Product B"); }
      }

      // 工厂接口
      public abstract class Creator {
      public abstract Product createProduct();
      }

      // 具体工厂
      public class ConcreteCreatorA extends Creator {
      public Product createProduct() {
      return new ConcreteProductA();
      }
      }

      public class ConcreteCreatorB extends Creator {
      public Product createProduct() {
      return new ConcreteProductB();
      }
      }

  2. 抽象工厂模式(Abstract Factory)
    • 定义:提供一个创建相关对象家族的接口,而无需指定具体类。

    • 特点:解决多个产品之间的一致性问题(同一个工厂创建相关产品)。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      // 抽象产品
      public interface Chair { void sit(); }
      public interface Table { void place(); }

      // 具体产品
      public class VictorianChair implements Chair {
      public void sit() { System.out.println("Sitting on a Victorian Chair"); }
      }
      public class ModernChair implements Chair {
      public void sit() { System.out.println("Sitting on a Modern Chair"); }
      }
      public class VictorianTable implements Table {
      public void place() { System.out.println("Placing items on a Victorian Table"); }
      }
      public class ModernTable implements Table {
      public void place() { System.out.println("Placing items on a Modern Table"); }
      }

      // 抽象工厂
      public interface FurnitureFactory {
      Chair createChair();
      Table createTable();
      }

      // 具体工厂
      public class VictorianFurnitureFactory implements FurnitureFactory {
      public Chair createChair() { return new VictorianChair(); }
      public Table createTable() { return new VictorianTable(); }
      }
      public class ModernFurnitureFactory implements FurnitureFactory {
      public Chair createChair() { return new ModernChair(); }
      public Table createTable() { return new ModernTable(); }
      }

  3. 建造者模式(Builder)
    • 定义:将一个复杂对象的构造与其表示分离,使相同的构建过程可以创建不同的表示。

    • 特点:逐步构建复杂对象,尤其适合对象有多个可选参数时。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      public class Product {
      private String partA;
      private String partB;
      public void setPartA(String partA) { this.partA = partA; }
      public void setPartB(String partB) { this.partB = partB; }
      public void show() { System.out.println(partA + ", " + partB); }
      }

      public interface Builder {
      void buildPartA();
      void buildPartB();
      Product getResult();
      }

      public class ConcreteBuilder implements Builder {
      private Product product = new Product();
      public void buildPartA() { product.setPartA("PartA"); }
      public void buildPartB() { product.setPartB("PartB"); }
      public Product getResult() { return product; }
      }

      public class Director {
      public void construct(Builder builder) {
      builder.buildPartA();
      builder.buildPartB();
      }
      }

  4. 原型模式(Prototype)
    • 定义:通过复制现有对象来创建新对象,而不是通过实例化类。

    • 特点:通过克隆方法快速创建对象,适合对象创建开销大的场景。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      public abstract class Prototype implements Cloneable {
      public Prototype clone() throws CloneNotSupportedException {
      return (Prototype) super.clone();
      }
      }

      public class ConcretePrototype extends Prototype {
      private String field;
      public void setField(String field) { this.field = field; }
      public String getField() { return field; }
      }

  5. 单例模式(Singleton)
    • 定义:确保某个类只有一个实例,并提供全局访问点。

    • 特点:常用于共享资源的访问。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      public class Singleton {
      private static Singleton instance;
      private Singleton() {}
      public static Singleton getInstance() {
      if (instance == null) {
      instance = new Singleton();
      }
      return instance;
      }
      }

结构型模式


结构型模式用于描述类和对象的组合方式,确保系统结构更灵活和可扩展。以下是常见的结构型模式:

  1. 适配器模式(Adapter)
    • 定义:将一个类的接口转换为客户端期望的接口,使原本不兼容的类可以协同工作。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      public interface Target {
      void request();
      }

      public class Adaptee {
      public void specificRequest() {
      System.out.println("Specific Request");
      }
      }

      public class Adapter implements Target {
      private Adaptee adaptee;
      public Adapter(Adaptee adaptee) {
      this.adaptee = adaptee;
      }
      public void request() {
      adaptee.specificRequest();
      }
      }

  2. 组合模式(Composite)
    • 定义:将对象组合成树状结构,客户端可以统一处理单个对象和对象组合。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      public abstract class Component {
      public abstract void operation();
      }

      public class Leaf extends Component {
      public void operation() { System.out.println("Leaf operation"); }
      }

      public class Composite extends Component {
      private List<Component> children = new ArrayList<>();
      public void add(Component component) { children.add(component); }
      public void operation() {
      for (Component child : children) {
      child.operation();
      }
      }
      }

  3. 装饰器模式(Decorator)
    • 定义:动态地给对象添加职责,而不影响其他对象的功能。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      public interface Component {
      void operation();
      }

      public class ConcreteComponent implements Component {
      public void operation() { System.out.println("Base Operation"); }
      }

      public class Decorator implements Component {
      protected Component component;
      public Decorator(Component component) { this.component = component; }
      public void operation() { component.operation(); }
      }

      public class ConcreteDecorator extends Decorator {
      public ConcreteDecorator(Component component) { super(component); }
      public void operation() {
      super.operation();
      System.out.println("Additional Operation");
      }
      }

行为型模式


行为型模式注重对象间的职责分配和协作方式。以下是常见的行为型模式:

  1. 观察者模式(Observer)
    • 定义:定义一对多的依赖关系,当对象状态发生变化时,自动通知依赖的观察者。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      public interface Observer {
      void update(String state);
      }

      public class Subject {
      private List<Observer> observers = new ArrayList<>();
      private String state;

      public void addObserver(Observer observer) {
      observers.add(observer);
      }

      public void setState(String state) {
      this.state = state;
      notifyObservers();
      }

      private void notifyObservers() {
      for (Observer observer : observers) {
      observer.update(state);
      }
      }
      }

      public class ConcreteObserver implements Observer {
      public void update(String state) {
      System.out.println("State changed: " + state);
      }
      }

  2. 迭代器模式(Iterator)
    • 定义:提供一种访问容器中元素的方法,而不暴露其内部结构。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      public interface Iterator<T> {
      boolean hasNext();
      T next();
      }

      public class ConcreteIterator<T> implements Iterator<T> {
      private List<T> list;
      private int index = 0;

      public ConcreteIterator(List<T> list) {
      this.list = list;
      }

      public boolean hasNext() {
      return index < list.size();
      }

      public T next() {
      return list.get(index++);
      }
      }

  3. 策略模式(Strategy)
    • 定义:定义一组算法,将每种算法封装到独立的类中,使其可以互换。

    • 示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      public interface Strategy {
      void execute();
      }

      public class ConcreteStrategyA implements Strategy {
      public void execute() { System.out.println("Executing Strategy A"); }
      }

      public class Context {
      private Strategy strategy;
      public Context(Strategy strategy) { this.strategy = strategy; }
      public void executeStrategy() { strategy.execute(); }
      }