1

Can we define a Singleton class without having getInstance() method?

public class Singleton {
    public static final Singleton singleton = new Singleton();
    private Singleton(){    
    }
}
class stacker
  • 5,357
  • 2
  • 32
  • 65
user3082820
  • 91
  • 2
  • 8
  • To what end? "In software engineering, the singleton pattern is a design pattern that restricts the Instantiation of a class to one object" - Implementation details don't matter so much as long as it fits the definition. – Mike B Dec 09 '13 at 12:47
  • Sure, and why would you want to do that? It's not following the Signleton design pattern, then, anymore. – class stacker Dec 09 '13 at 12:47
  • Voted to close as unclear since OP doesn't seem eager to answer questions – Mike B Dec 09 '13 at 13:16
  • I have a simple question. Is above code an example of singleton? – user3082820 Dec 10 '13 at 04:43

1 Answers1

0

You should separate the concept of an object that only has a single instance from the singleton pattern. You can find a discussion of the two here and here. TL;DR Single instance is useful, while using the singleton pattern is bad.

The best way to use a single-instance object in your code is to pass it via ctor. This is easier with a dependency injection framework, but works without, too.

class Something
{
    private IMySingleInstance _single;

    public Something(IMySingleInstance s)
    {
        _single = s;
    }
}

If you do it like that, you declare the dependency, and you can actually test your Something and mock the single instance if necessary without all the problems related to the singleton pattern.

Community
  • 1
  • 1
Wilbert
  • 7,251
  • 6
  • 51
  • 91
  • I am aware of design concepts but I am interested to know technical difficulties by not using getInstance() method. – user3082820 Dec 10 '13 at 04:33
  • The technical difficulties are not regarding the getInstance, but using static. Single-instance / singleton implementations using static lead to problems and should be avoided. – Wilbert Dec 11 '13 at 09:07