I have the following class:
public class NinjaImpl implements Ninja{
private NinjaImple () {}
public static Ninja getInstance() {return Singleton.instance;}
private static class Singleton
{
private static final Ninja instance = new NinjaImpl();
}
// Implementation
}
I have a design discussion with a colleague. Should the inner class hold a variable of type NinjaImpl or of type ninja. In the same way should getInstance()
return Ninja or NinjaImpl?
Normally getInstance()
should return the interface, as it allows you to change the implementing class without affecting the users of the interface.
However, since in your case getInstance()
is a method of the implementing class, the users of getInstance()
already have a dependency on the implementing class regardless of the type it returns, so it doesn't really matter, and I'm not sure it is even useful to define the Ninja
interface at all in this case.
It would make more sense to return the interface if getInstance()
would be a method of some factory class (lets call it NinjaFactory
), which may return any implementation of the Ninja
interface it chooses to return.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.