This question already has answers here:
How to instantiate a Singleton multiple times?
(9 answers)
Closed 9 years ago.
I have created a Singleton class using lazy initialization method. That is the getInstance method is synchronized. But without changing the design pattern is there a way to create multiple instances of the Singleton class. Because changing the Singleton pattern will take lot of architectural changes. Please advice a way to create multiple instances. Please help in Java.
Singleton patten means only one instance is allowed. So there is no question of creating multiple instances.
Though there are some hacks and workarounds like Serializing the Object and De Serializing it back or using different Class loaders but again it violates the basic principle why Singleton pattern is created for.
EDIT: I don't have the required reputation to add it as a comment hence adding it as an answer - as pointed out in the comments, it's a possible duplicate.
A little research and there you have it:
Reference this link
Code
class MySingleton {
private MySingleton() {
}
}
class Test {
public void test() throws Exception {
Constructor<MySingleton> constructor = MySingleton.class.getConstructor();
constructor.setAccessible(true);
MySingleton otherSingleton = constructor.newInstance();
}
}
You want to have multiple instances of a class which can only have one instance by design.
You can, but it is no longer a singleton. Treat it as a normal object which have multiple instances and the restriction is lifted. How you do that depends on your use case.
It will depend on the class behaviour. If the instance is well encapsulated, you can recreate what getInstance method does using reflection, I guess.
Related
This question already has answers here:
difference between class level instantiation vs method instantiation
(6 answers)
Closed 6 years ago.
Is there a difference in class and local instantiation when the first one is not obligatory (usually when i can finalize them)? Is there a "rule" i should follow?
I have developed the habit to always instantiate other classes using class instantiation and i don't really know if this is bad.
public class aService {
private final SomeClass someClass = new SomeClass();
public void someMethod() {
someClass.doSomething();
}
}
// or
public class aService {
public void someMethod() {
SomeClass someClass = new SomeClass();
someThing.doSomething();
}
}
I would prefer initialize someClass in given method if it is used only in that method.
If you want to use someClass across all methods (more than one) and store object state, then choose solution 1.
First approach is better when you want optimization, because someClass is created only once. On the other hand, you may never call someMethod(). In this case you waste memory. Especially if you have lot of such objects
If the situation you describe is a single-use method which is instantiated once to serve a specific purpose, after which its instance does not need to exist anymore, then I would prefer neither of these options. Both create an instance unnecessarily.
Instead, I'd rather focus on making the method that I care about in SomeClass static. The chief reason is that I can save an unneeded instantiation of an object and make the API and its usages a lot smoother.
There is no "rule" per se, but as it is related to development the rule is related to good clean developer code guidelines...
calss fields/ variables should be initialized in the constructor... that is the constructor's job.
constants can be declared and init in the same line for obvious reasons...
This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 6 years ago.
what is the better approach?
Let us assume a scenario in which there is a utility class that is used by other classes. What is better to use in this case, a singleton class which can be instantiated exactly once or should i make all the fieds static?
In object-oriented programming generally you should avoid singletons and utility classes if possible.
However, if really needed I'd go with utility class without any fields - just static methods. By definition utilities should be rather set of stateless functions. Such are well testable in comparison to untestable singleton (which is done with static field). If you need to keep the state then go towards true objects.
As stated in the comment, you can have a safe singleton done by dependency injection, without static state.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods.
As far as I can find out, there might be two possible answers to it -
When your class needs to have state and you want only one object of it. From the design point of view, class with static methods & variables are considered to be the Utility classes and shouldn't be keeping any state.
If your class needs to take part in polymorphism and you want only one object of the class(es) which are in the inheritance tree.
It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism / Inheritance?
Collections.emptySet() is a typical example of a singleton that can't be implemented as a static class since, obviously, its goal is to be an instance of the java.util.Set interface. It's not costly to create, but it would be stupid to create a new instance each time an empty set is needed, since the unique instance can be reused.
Classes that perform logging or common access to data bases frequently follow the Singleton pattern. Basically anything that should have instance methods and that is costly to construct.
Scope and behavior are different concerns and should NOT be mixed. You may want your object to be available per use, per thread, per web request, per session or global (Singleton). The reasons for making these adjustments are likely due to resource management and ultimately performance. The behavior inside your class shouldn't have to change if you change its scope.
Singleton is pattern for taking a regular object and controlling its scope with just a little bit of bolt-on code. Ideally though, you really shouldn't really deal with scope at all inside your object and delegate that to a factory or container.
My answer is quite short but it's enough to use exactly common singleton instead of it's static implementation. The answer is:
Popular paradigm (yes it is!)
Threads (synchronization etc.)
Interface implementation (your static class has some restrictions)
Is there any method to check whether any instance of a class is running?
I have a GUI and I don't want open another instance of it, if a one is already running.
I know about including a counter in constructor. Any method except that?
Thanks in advance!!
Use the singleton pattern.
Here is a simple implementation in java of a singleton:
public class MyClass {
private static MyClass INSTANCE = new MyClass();
private MyClass() { // private constructor prevents creation outside class
}
public static MyClass getInstance() {
return INSTANCE;
}
}
Note that this is not "bulletproof" (there are "hacks" you can use via reflection to circumvent this and create two instances), however if you're the only user of the code it will be fine.
Is there any method to check whether any instance of a class is running?
The simple answer is No.
The normal way to deal with this problem is to use the Singleton design pattern. The idea of the pattern is that you write the code to remove the possibility of creating multiple instance of the class.
In Java you typically do this by declaring the class constructor to be private, and providing access to the singleton instance via a static method. Depending on your precise requirements, the singleton can be created eagerly or lazily.
Bohemian's answer provides a good example of this approach.
(In Java 5 or later, it is also possible to use enum types to implement singletons.)
Use Enum as recommended by J. Bloch (Effective Java Programming 2nd Ed., Addison Wesley)
In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example