싱글 톤이 나쁘면 서비스 컨테이너가 좋은 이유는 무엇입니까?
우리는 Singleton 이 얼마나 나쁜지 알고 있습니다. 그 이유는 의존성을 숨기고 있기 때문 입니다.
그러나 프레임 워크에는 한 번만 인스턴스화 하고 모든 곳 (로거, DB 등) 에서 호출해야하는 많은 개체가있을 수 있습니다 .
이 문제를 해결하기 위해 서비스 (로거 등)에 대한 모든 참조를 내부적으로 저장하는 소위 "개체 관리자"(또는 심포니와 같은 서비스 컨테이너 ) 를 사용하라는 지시를 받았습니다.
하지만 서비스 제공 업체가 순수한 싱글 톤만큼 나쁘지 않은 이유는 무엇입니까?
서비스 공급자는 종속성도 숨기고 첫 번째 인스턴스 생성을 래핑합니다. 그래서 싱글 톤 대신 서비스 제공 업체를 사용해야하는 이유를 이해하기 위해 정말 고심하고 있습니다.
추신. 종속성을 숨기지 않으려면 DI를 사용해야한다는 것을 알고 있습니다 (Misko가 말한대로)
더하다
나는 추가 할 것이다 : 요즘 싱글 톤은 그렇게 사악하지 않다. PHPUnit의 제작자는 여기에서 설명했다.
DI + Singleton은 문제를 해결합니다.
<?php
class Client {
public function doSomething(Singleton $singleton = NULL){
if ($singleton === NULL) {
$singleton = Singleton::getInstance();
}
// ...
}
}
?>
이것이 모든 문제를 전혀 해결하지 못하더라도 꽤 똑똑합니다.
DI 및 서비스 컨테이너 외에이 도우미 개체에 액세스 할 수있는 좋은 솔루션이 있습니까?
서비스 로케이터는 말할 것도없이 두 가지 악 중 더 적은 것입니다. 이 네 가지 차이점으로 요약되는 "작은"( 적어도 지금 당장은 다른 것을 생각할 수 없습니다 ) :
단일 책임 원칙
Service Container는 Singleton처럼 단일 책임 원칙을 위반하지 않습니다. 싱글 톤은 객체 생성과 비즈니스 로직을 혼합하는 반면, 서비스 컨테이너는 애플리케이션의 객체 수명주기를 관리하는 책임이 있습니다. 그런 점에서 서비스 컨테이너가 더 좋습니다.
커플 링
싱글 톤은 일반적으로 정적 메서드 호출로 인해 애플리케이션에 하드 코딩되므로 코드에서 밀접하게 결합되고 모의 종속성 이 발생하기 어렵습니다 . 반면에 SL은 하나의 클래스이며 주입 될 수 있습니다. 따라서 모든 클래스가 그것에 의존하지만 적어도 느슨하게 결합 된 종속성입니다. 따라서 ServiceLocator를 Singleton 자체로 구현하지 않는 한 다소 더 좋고 테스트하기도 쉽습니다.
However, all classes using the ServiceLocator will now depend on the ServiceLocator, which is a form of coupling, too. This can be mitigated by using an interface for the ServiceLocator so you are not bound to a concrete ServiceLocator implementation but your classes will depend on the existence of some sort of Locator whereas not using a ServiceLocator at all increases reuse dramatically.
Hidden Dependencies
The problem of hiding dependencies very much exists forth though. When you just inject the locator to your consuming classes, you wont know any dependencies. But in contrast to the Singleton, the SL will usually instantiate all the dependencies needed behind the scenes. So when you fetch a Service, you dont end up like Misko Hevery in the CreditCard example, e.g. you dont have to instantiate all the depedencies of the dependencies by hand.
Fetching the dependencies from inside the instance is also violating Law of Demeter, which states that you should not dig into collaborators. An instance should only talk to its immediate collaborators. This is a problem with both Singleton and ServiceLocator.
Global State
The problem of Global State is also somewhat mitigated because when you instantiate a new Service Locator between tests all the previously created instances are deleted as well (unless you made the mistake and saved them in static attributes in the SL). That doesnt hold true for any global state in classes managed by the SL, of course.
Also see Fowler on Service Locator vs Dependency Injection for a much more in-depth discussion.
A note on your update and the linked article by Sebastian Bergmann on testing code that uses Singletons : Sebastian does, in no way, suggest that the proposed workaround makes using Singleons less of a problem. It is just one way to make code that otherwise would be impossible to test more testable. But it's still problematic code. In fact, he explicitly notes: "Just Because You Can, Does Not Mean You Should".
The service locator pattern is an anti-pattern. It doesn't solve the problem of exposing dependencies (you can't tell from looking at the definition of a class what its dependencies are because they aren't being injected, instead they are being yanked out of the service locator).
So, your question is: why are service locators good? My answer is: they are not.
Avoid, avoid, avoid.
Service container hides dependencies as Singleton pattern do. You might want to suggest using dependency injection containers instead, as it has all the advantages of service container yet no (as far as I know) disadvantages that service container has.
As far as I understand it, the only difference between the two is that in service container, the service container is the object being injected (thus hiding dependencies), when you use DIC, the DIC injects the appropriate dependencies for you. The class being managed by the DIC is completely oblivious to the fact that it is managed by a DIC, thus you have less coupling, clear dependencies and happy unit tests.
This is a good question at SO explaining the difference of both: What's the difference between the Dependency Injection and Service Locator patterns?
Because you can easily replace objects in Service Container by
1) inheritance (Object Manager class can be inherited and methods can be overriden)
2) changing configuration (in case with Symfony)
And, Singletons are bad not only because of high coupling, but because they are _Single_tons. It's wrong architecture for almost all kinds of objects.
With 'pure' DI (in constructors) you will pay very big price - all objects should be created before be passed in constructor. It will mean more used memory and less performance. Also, not always object can be just created and passed in constructor - chain of dependencies can be created... My English are not good enough to discuss about that completely, read about it in Symfony documentation.
For me, I try to avoid global constants, singletons for a simple reason, there are cases when I might need to APIs running.
For example, i have front-end and admin. Inside admin, I want them to be able to login as a user. Consider the code inside admin.
$frontend = new Frontend();
$frontend->auth->login($_GET['user']);
$frontend->redirect('/');
This may establish new database connection, new logger etc for the frontend initialization and check if user actually exists, valid etc. It also would use proper separate cookie and location services.
My idea of singleton is - You can't add same object inside parent twice. For instance
$logger1=$api->add('Logger');
$logger2=$api->add('Logger');
would leave you with a single instance and both variables pointing to it.
Finally if you want to use object oriented development, then work with objects, not with classes.
'IT박스' 카테고리의 다른 글
| 레코드가 없을 때 nil과 함께 find () (0) | 2020.09.09 |
|---|---|
| 레일에서 열 유형을 더 긴 문자열로 변경 (0) | 2020.09.09 |
| Mac에서 $ PATH에 / usr / local / bin을 추가하는 방법 (0) | 2020.09.08 |
| 루비에서 스레드로부터 안전하지 않은 것이 무엇인지 아는 방법? (0) | 2020.09.08 |
| 신뢰할 수있는 UDP가 필요할 때 무엇을 사용합니까? (0) | 2020.09.08 |