gpt4 book ai didi

java - 观察者设计模式方法在做 2 件事时是否违反 SRP : setting and notifying

转载 作者:行者123 更新时间:2023-11-29 04:20:34 26 4
gpt4 key购买 nike

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

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

如果否,那么我们如何才能正确理解 SRP?提前谢谢你。

我也关注 this topic但找不到合适的答案。

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...]
}

最佳答案

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

引用“清洁代码”第 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 件事(处理更改),“集合上面引用中下一个抽象级别的步骤)。

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

关于java - 观察者设计模式方法在做 2 件事时是否违反 SRP : setting and notifying,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49491170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com