9

I need to create a singleton class without keeping a static method.

How can i do that?

  • Only call the constructor once. – M Platvoet Dec 22 '11 at 10:43
  • 2
    @M Platvoet - That's not a singleton, because you can call the constructor a second time. – Petar Minchev Dec 22 '11 at 10:43
  • 1
    @Peter, wrong. That's not a singleton pattern, it is however a singleton instance. – M Platvoet Dec 22 '11 at 10:46
  • @M Platvoet - Wrong, the OP asks for a singleton class and I was talking about singleton pattern, not instance. – Petar Minchev Dec 22 '11 at 10:55
  • @Peter Did you really want to get down Sunny on his interview? ;) – andrey Dec 22 '11 at 10:56
21

Create an enum with one instance

enum Singleton {
    INSTANCE;

    private Field field = VALUE;
    public Value method(Arg arg) { /* some code */ }
}

// You can use
Value v = Singleton.INSTANCE.method(arg);

EDIT: The Java Enum Tutorial shows you how to add fields and methods to an enum.


BTW: Often when you can use a Singleton, you don't really need one as utility class will do the same thing. The even shorter version is just

enum Utility {;
    private static Field field = VALUE;
    public static Value method(Arg arg) { /* some code */ }
}

// You can use
Value v = Utility.method(arg);

Where Singletons are useful is when they implement an interface. This is especially useful for testing when you using Dependency injection. (One of the weakness of using a Singleton or utility class substitution in unit tests)

e.g.

interface TimeService {
    public long currentTimeMS();
}

// used when running the program in production.
enum VanillaTimeService implements TimeService {
    INSTANCE;
    public long currentTimeMS() { return System.currentTimeMS(); }
}

// used in testing.
class FixedTimeService implements TimeService {
    private long currentTimeMS = 0;
    public void currentTimeMS(long currentTimeMS) { this.currentTimeMS = currentTimeMS; }
    public long currentTimeMS() { return currentTimeMS; }
}

As you can see, if your code uses TimeService everywhere, you can inject either the VanillaTimeService.INSTANCE or a new FixedTimeService() where you can control the time externally i.e. your time stamps will be the same every time you run the test.

In short, if you don't need your singleton to implement an interface, all you might need is a utility class.

|improve this answer|||||
  • @Pater Thanks for the quick reply – Sunny Gupta Dec 22 '11 at 10:44
  • I don't get it ... you can't call any method on your singleton – remi bourgarel Dec 22 '11 at 16:56
  • @remi bourgarel a java enum is just a class. Just add the variables, methods and a constructor to the Singleton enum (after the declaration of INSTANCE) as you would with any other class and INSTANCE has them. – josefx Dec 22 '11 at 18:13
  • @remibourgarel I have added a link, I hope that helps. ;) – Peter Lawrey Dec 23 '11 at 8:23
2

Another approach is the singleton holder idiom which offers initialization on demand:

public class Something {
        private Something() {
        }

        private static class LazyHolder {
                public static final Something INSTANCE = new Something();
        }

        public Something getInstance() {
                return LazyHolder.INSTANCE;
        }
}

(Example modified, made getInstance method not static)

Note that standalone singletons like this should be avoided where possible because it promotes global state, leads to hard-to-unittest code and depends on a single classloader context to name a few possible drawbacks.

|improve this answer|||||
8
public class Singleton {
    public static final Singleton instance = new Singleton();
    private Singleton() {}
    public void foo() {}
}

then use

Singleton.instance.foo();
|improve this answer|||||
  • 1
    For completeness: Please add a private no-arg constructor. – A.H. Dec 22 '11 at 11:12
  • Great! Thank you A.H.! (My regular mistake :) – andrey Dec 22 '11 at 11:27
0

From within constructor you need to chceck if there is already instance of the class somewhere. So you need to store reference to your singleton instance in static variable or class. Then in contructor of singleton I would always check if there is existing instance of singleton class. If yes I wouldnt do anything if not I would create it and set reference.

|improve this answer|||||
0

Use an object factory, fetch your singleton object from this factory.

ObjectFactory factory;
....
MySingletonObject obj = factory.getInstance(MySingletonObject.class);

of course, there are many frameworks to help you to achieve this. the spring framework is a popular choice.

|improve this answer|||||
  • Isnt factory using a static method? That is something he doesn want. – Eduard Dec 22 '11 at 10:54
1

You can use one of IoC containers (e.g. Google Guice) and use your class as singleton(eager or lazy - it depends on your needs). It's easy and flexible as instantiating is controlled by IoC framework - you don't need any code changes if, for example, you will decide to make your class not singleton later.

|improve this answer|||||
  • In the context of an interview question it is not a good idea to solve little problems like that by introducing huge frameworks like an IoC container. – A.H. Dec 22 '11 at 11:16
  • Why? IoC is quite an ordinary thing now. And it's a plus if interviewee knows about it and propose using IoC framework as one of possible solutions. – Artem Dec 22 '11 at 11:19
  • Yes, IoC is common knowlegde nowaday. By far it is not used in all and every project. So unless the the interviewer showed an interest in any IoC framework before, I would assume that the question wants to test the knowledge about the language itself. If you don't show that you know how simple things can be done in a simple way but only in a complicated way involving several heavy frameworks then it can be assumed, that your normal problem solving skill works the same way. <br/>The best thing to do: Show both solutions. – A.H. Dec 22 '11 at 12:17
1

Follow the Joshua Bloch enum recipe in "Effective Java" 2nd edition. That's the best way to create a singleton.

I don't understand why this comes up so much. Isn't singleton a discredited design pattern? The GoF would vote it off the island today.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.