What does this code mean?

眉间皱痕 提交于 2019-12-13 17:22:27

问题


I do not know, what is function of code lookups.singleton in code below

public class ProjectNode extends AbstractNode {

public ProjectNode(MainProject obj, ProjectsChildren children) {
    super (children, Lookups.singleton(obj));
    setDisplayName ( obj.getName());
}
}

回答1:


You can read about the NetBeans Platform's Lookup apis to get an overview of the design pattern. You can also read about the class named Lookups, for details about its methods.

Basically, this API creates a lookup object that only contains a single object. When the you call lookup on this object will only return the object that was used to initialize the object, if it implements/extends the object that is used in the query.

The Lookup pattern is a very important part of the NetBeans platform.




回答2:


Lookups is what is generally called a Service Locator and it's generally viewed as an anti-pattern these days but was quite common 5-8 years ago. The singleton() method is a public static method on the class that is used to essentially find a reference to a basically global object. Imagine it looks like:

public class Lookups {
  public static SomeObject singleton(InputObject obj) {
    // use the parameter to return some other object
  }
}

The reason it's viewed as an anti-pattern is that it can make it extremely difficult to unit test or mock sections of your code. In Java DI ("dependency injection") frameworks like Spring tend to be favoured over this approach.



来源:https://stackoverflow.com/questions/2504560/what-does-this-code-mean

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