[英]SOLID priciples - Single Responsible is just about composition or also dependency inversion?
I have seen examples online about the Single Responsible principle.我在网上看到过关于单一责任原则的例子。
They always use IoC/DI as an example.他们总是以 IoC/DI 为例。
They move the code from class A to class B and pass class B as reference.他们将代码从 class A 移至 class B,并传递 class B 作为参考。
See code below:请参阅下面的代码:
class B {}
class A {
b;
// reference used
constructor(b) {
this.b = b;
}
doStuff() {
...
this.b.doSomeOtherStuff();
}
}
But the Single Responsible principle is about to increase the coherence.但是单一责任原则即将增加连贯性。
Theoretically the code above would also follow the Single Reponsible principle without从理论上讲,上面的代码也将遵循单一责任原则,而无需
passing down a reference to class B, right?传递对 class B 的引用,对吗?
Like this:像这样:
class B {}
class A {
// no reference
constructor() {
this.b = new B;
}
doStuff() {
...
this.b.doSomeOtherStuff();
}
}
In the book Clean Code by Robert C. Martin there is an example reagarding the SRP where he uses only composition.在 Robert C 的 Clean Code 一书中,Martin 有一个关于 SRP 的例子,他只使用组合。
So I would say yes, Singe Responsible Priciple is valid without IoC/DI.所以我会说是的,单一责任原则在没有 IoC/DI 的情况下是有效的。
In the example below hes directly creating an instance of the LinkedList.在下面的示例中,他直接创建了 LinkedList 的实例。
public class Stack {
private int topOfStack = 0;
// creating a direct instance here
List < Integer > elements = new LinkedList < Integer > ();
public int size() {
return topOfStack;
}
public void push(int element) {
topOfStack++;
elements.add(element);
}
public int pop() throws PoppedWhenEmpty {
if (topOfStack == 0)
throw new PoppedWhenEmpty();
int element = elements.get(--topOfStack);
elements.remove(topOfStack);
return element;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.