views:

131

answers:

2

Hello, 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());
}
}
+3  A: 

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.

cletus
And which simple pattern can replace this anti pattern?
joseph
@joseph is this a Web app, desktop app, something else? Are you using Spring already?
cletus
it is desktop, I use only netbeans PLATFORM. I am going by the tutorial on platform.netbeans.org, and I have no idea, which pattern I can use instead of this quite hardly understandable lookups.
joseph
@Cletus, I wouldn't worry about it right now, just do what you can. It's not a terrible pattern actually... just can be a little uncomfortable for unit testing which is probably not your biggest worry right now. What it does is examine the input object and make some decision as to which "SomeObject" to return to you based on the parameter passed in--or perhaps it simply stores a reference to your MainProject object inside "SomeObject" as it creates it. In short, it gives you an object that is somehow related to the one being passed in.
Bill K
+2  A: 

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.

vkraemer