观察者设计模式方法在做两件事时是否违反了 SRP:设置和通知

Does observer design pattern method violate SRP when do 2 things: setting and notifying

我刚刚从 this link 的观察者设计模式中阅读了这个示例代码。但是,谁能解释一下 setState 方法 (不询问 Subject class)是否在做两件事(设置 state 并通知 observers)?

如果是,那么方法 setState 是否违反了单一职责原则 (SRP)?

如果不是,那我们怎么才能正确理解SRP呢?提前谢谢你。

我也关注了但是找不到合适的答案

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

   public void setState(int state) {
     this.state = state;
     notifyAllObservers();
   }

   public void notifyAllObservers(){
     for (Observer observer : observers) {
        observer.update();
     }
   }

   // [...omitted other unrelated methods...]
}

我要引用 Robert C. Martin(鲍勃叔叔)的话:

SRP: The Single Responsibility Principle There should never be more than one reason for a class to change.

(ref.)

所以 class 可以 做不止一件事,只要它只有一个改变的理由。

我会说你很好。

问题明确是关于方法 'setState' 是否做了 2 件事。答案是否定的。

引用 'Clean Code' 第 36 页:

If a function does only those steps that are one level below the stated name of the function, then the function is doing one thing. After all, the reason we write functions is to decompose a larger concept (in other words, the name of the function) into a set of steps at the next level of abstraction. ... So, another way to know that a function is doing more than 'one thing' is if you can extract another function from it with a name that is not merely a restatement of its implementation.

困难在于名称 'setState(int state)' 表明函数设置状态(使用 this.state = state;)然后调用另一个函数,做两件事。

public void setState(int state) {
 this.state = state;
 notifyAllObservers();

}

但是,如果我们将函数重命名为 processChange() ,则很明显该函数分两步(1. 设置状态和 2. 通知观察者)做 1 件事(处理更改),'set of steps at the next level of abstraction' 在上面的引用中)。

public void processChange(int state) {
 this.state = state;
 notifyAllObservers();

}

给定 link 中的示例不是很好,命名 setState() 会引起混淆,因为它没有通知(与设置无关)。

将名称更改为例如processStateChanged()在这种情况下会有所帮助。