Registry pattern Vs Service locator pattern Vs Dependency Injection Container

故事扮演 提交于 2019-12-03 10:49:58

问题


Is there any difference between them rather than set and get objects in an array by key?

class Registry
{
private $container=array();
  public static function Set($name,$object){
    self::$container[$name]=$object;
  }
  public static function &Get($name){
  return self::$container[$name];
  }
}

回答1:


Registry Pattern

Registry pattern is a pattern used to lookup an object knowing only its name. This pattern stores instances of objects internally and uses a dictionary mapping to retrieve those instances later.

DI Container/DI Pattern

A DI container contains a registry which has a mapping of object types to abstractions. It is more advanced in that when an object is resolved it is instantiated, and so are all of the object's dependencies.

When you request an object from a DI container, you get an object graph starting with the object you request as the root. Each dependent object is injected automatically by recursively going through the constructor of each class, starting at the classes that have no dependencies and instantiating each object using the registry as a guide.

Dependency Injection is a pattern that doesn't necessarily use a DI container. The DI pattern is comprised of a composition root which sits at the entry-point of the application. The composition root is where the types are registered and where the root object graph is instantiated. Once the root object is instantiated, the application runs on its own. The application itself has no reference to the DI container and is not tightly coupled to it.

Service Locator

Service locator is considered by many people to be anti-pattern. The idea is that you either inject the container into your object or use a static reference to the DI container to create instances at runtime.

The primary difference is that the application is explicitly dependent on (thus tightly-coupled to) the DI container.

Another disadvantage of using Service Locator is that because you are injecting the DI container, it is not possible to see from the class constructors what interfaces it is dependent on. You instead have to consult the documentation or analyze the source code to determine what a class's dependencies are.

Although considered anti-pattern, there are still some situations where it makes sense to use. However, it should be considered a last resort after all other options (ambient context, property injection, etc.) have been exhausted.



来源:https://stackoverflow.com/questions/27854298/registry-pattern-vs-service-locator-pattern-vs-dependency-injection-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!