No Static Method in Interface, So I Write Code As ...
Java does not support static method in interface. But sometimes, I just want a static method to say: PersistenceManager.getDefault(), where PersistenceManager is going to be an interface. I don't like to add one more class named PersistenceManagerFactory, with a method:
public static PersistenceManager PersistenceManagerFactory.getDefault()
So I write code like:
public class PersistenceManager {
private static I i;
public static I getDefault() {
return i == null ? i = ServiceLoader.load(I.class).iterator().next() : i;
}
/** The interface I, which is actually the PersistenceManager should be: */
public static interface I {
void saveQuotes(String symbol, Frequency freq, List quotes);
List restoreQuotes(String symbol, Frequency freq);
void deleteQuotes(String symbol, Frequency freq, long fromTime);
void dropAllQuoteTables(String symbol);
void shutdown();
QuotePool getQuotePool();
TickerPool getTickerPool();
}
}
Then implement the PersistenceManager.I in another package, like:
public class NetBeansPersistenceManager implements PersistenceManager.I {
...
}
And declare it under the META-INF as:
core/src/META-INF/services/org.aiotrade.math.PersistenceManager$I
which contains one line:
org.aiotrade.platform.core.netbeans.NetBeansPersistenceManager
I can call PersistenceManager.getDefault().showdown() now.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/blog_logo.png)
rss
Comments
Another way is to keep the interface having a sane name, and make the static method be part of a static class declared in the interface.
One has to question what the advantage of an interface is in this case; when all the instances are intended to be derived from one implementation, if that is indeed the intention.
One may choose instead to make this into a simple class with a constructor.
In my case, the PersistenceManager?(service) and the implement are defined in two different modules. The implement depends on NetBeans APIs, which should be decoupled from the general purpose Math modules. So I separate the interface and implement. The Math module just call PersistenceManager?.getDefault() and do something, doesn't care how it's implemented, this gives the potential to implement another PersistenceManager? that may depend on database, xml, txt etc.
Hi Caoyuan,
This article might shed light on another way to program on interface.
http://martinfowler.com/articles/injection.html
Cheers,
Eneratom
Hi Eneratom,
IoC is used everywhere in NetBeans Platform. My experience is that when apply NetBeans' module system to decouple a package out to a module, it force me to do a lot of IoC, that's very good.
For this example, what I meant was the 'I' letter I used, it meant 'interface' or 'I'(me), that's what I like.
Regards, Caoyuan