usage of static

hi,

i have a class DepthSearch that runs an depth search algorithm on a graph.

The DepthSearch class provides the method search(Graph, node), which returns an boolean whether the node exists or not.

now i can realize it in two different ways:

1. make the searchMethod static

and invoke it like

int result = DepthSearch.search(graphInstance, nodeA);

2. use the following:

publicclass Factory{

privatestatic DepthSearch depthSearch;

private Factory{}

publicstatic DepthSearch getDepthSearchInstance(){

if(depthSearch ==null) depthSearch =new DepthSearch();

return depthSearch;

}

}

and use it like:

DepthSearch depthSearch = DepthSearchFactory.getDepthSearchInstance();

int result = depthSearch.search(graphInstance, nodeA);

what is the best way?

Thanks for answers in advance!

[1492 byte] By [Cinimooda] at [2007-10-3 7:55:15]
# 1

> what is the best way?

The question as posed has no answer.

Does the DepthSearch class maintain any state, or is it just a class full of utility methods that operate on other objects? If the former, you'll want to instantiate depth search and make the method non-static. If the latter, static might be appropriate.

Might you want to have different implementations of DepthSearch? Or might DepthSearch itself be an implementation of an interface, say, Seach, where there might also be, e.g., BreadthSearch? If so, then you probably want to make the search method non-static, and instantiate a DepthSearch on which to call it. Doing this lets you use polymorphism, so that the code that requests the search doesn't have to know or care which kind of search it will get.

Search search = SearchFactory.getSearch(); // might be Depth, might be Breadth

search.search(...);

jverda at 2007-7-15 2:57:46 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
I tend to only declare things as static if they really have to be.In your code, why do you use a (non-threadsafe) singleton pattern? What benefit do you get from that?
dubwaia at 2007-7-15 2:57:46 > top of Java-index,Other Topics,Patterns & OO Design...