Consider the following implementation
public enum Singleton {
INSTANCE;
private final OnlyOne onlyOne;
Singleton() {
onlyOne = new OnlyOne();
}
public static Singleton getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
Singleton one = getInstance();
one.onlyOne.method();
}
}
class OnlyOne {
public void method() {
System.out.println("Hello World");
}
}
Here I have tried to implement the Singleton using enum. I want OnlyOne to have just one instance. My question is how do I restrict clients from instantiating objects of class OnlyOne? Because in some other class we can easily do this
OnlyOne one = new OnlyOne();
I cannot provide a private constructor for it because doing so will break this
Singleton() {
onlyOne = new OnlyOne();
}
Do I need to use the enum as an inner member of OnlyOne class ? Any suggestions?
INSTANCE itself is the singleton. Add your method directly to the enum.
public static void main(String[] args) {
Singleton.INSTANCE.method();
}
public enum Singleton {
INSTANCE;
public void method() {
System.out.println(this);
}
}
Related
Is there a way where we can restrict a class to create only a single object in java? It should give some exceptions if we try to create another new object.
Example:
class A {}
public class Test {
public static void main(String[] args) {
A a1 =new A(); //This should be allowed
A a2 =new A(); // This should not be allowed
}
}
to try your additional requirement:
This should work, but I don't really see a point to it.
public class A {
private static boolean instantiated;
public A() throws Exception {
if ( instantiated ) {
throw new Exception("Already instantiated");
}
instantiated = true;
}
}
You can use the special Singleton pattern. Most of the examples are on the internet.
public class Singleton {
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
In my Java program, I am attempting to ensure that only one object of the class "ATM" is created. For this, I have a classic singleton class as below:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
How do I ensure that only one object of the class ATM is made? E.g. Where do I now put the code:
ATM theATM = new ATM();
Does this code belong in the singleton class, or within the ATM class?
You don't need that Singleton class, because your singleton has to be ATM.
So, just use this in ATM.java:
public class ATM {
private static ATM uniqueInstance;
private ATM() {}
public static ATM getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new ATM();
}
return uniqueInstance;
}
}
Now, you can call your line:
ATM theATM = new ATM();
only if you are in the ATM class itself, because your constructor is private, but this is useless because you care about uniqueInstance in this situation.
If you are in a different class, you should use:
public class Main {
public static void main(String[] args) {
ATM theATM = ATM.getInstance();
}
}
The idea of the singleton pattern is that even if you run again ATM.getInstance();, the same (initial) instance (uniqueInstance) will be returned. If it wasn't initialized before, it is initialized. Otherwise, the old instance is returned. So, this is how you are sure that you won't have multiple instances.
Of course, there are better implementations of the singleton pattern that are thread safe.
E.g.:
thread safe - lazy:
public class ATM {
private static ATM uniqueInstance = null;
private ATM(){}
public static synchronized ATM getInstance() {
if ( uniqueInstance == null ) {
uniqueInstance = new ATM();
}
return uniqueInstance;
}
}
thread safe - eager
public class ATM {
private static ATM uniqueInstance = new ATM();
private ATM(){}
public static ATM getInstance() {
return uniqueInstance;
}
}
thread safe - using enum
public enum ATM {
UNIQUE_INSTANCE;
...
}
Example class with singleton design pattern.
class Singleton {
private static Singleton instance;
private int x;
private Singleton() {
x = 5;
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Hello");
}
}
I'm just wondering can I create this class with same variables and methods declared as static. Is it same as the singleton?
Singleton should be considered only if all three of the following criteria are satisfied:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
Yes, It is the same.
If you really need to implement a singelton pattern I would recommend using an enum:
public enum MySingelton{
INSTANCE;
private final String[] variable = new String[]{"test", "test2};
public void randomFunction(){
}
}
Call it with:
MySingelton.INSTANCE.randomFunction();
With an enum implementation it's guaranteed that only one instance is created and that it's available all the time. Also it's possible to serialize and deserialize the singelton without creating multiple copies of it.
More information can be found here:
What is an efficient way to implement a singleton pattern in Java?
http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=3
Since the purpose of the singleton pattern is to ensure that a single instance of a class exists, yes, you could use static members to achieve the same effect.
So instead of
public class Singleton {
private static Singleton theInstance = new Singleton();
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
return theInstance;
}
}
you could do
public class FakeSingleton {
private static int aVar = 10;
public static void aMethod() {
System.out.println(aVar);
}
}
and have exactly the same functionality (instead of Singleton.getInstance().aMethod() you would write FakeSingleton.aMethod()).
Using the singleton pattern can be advantageous if you want lazy initialization, so that the singleton is only initialized when it is first needed, as follows:
public class Singleton {
private static Singleton theInstance = null;
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
if (theInstance == null) {
theInstance = new Singleton();
}
return theInstance;
}
}
(Note that the above is not thread-safe, in multithreaded code you will need to add synchronization.)
I've got quite disturbing problem with singleton in my project.
I created a class called Singleton (how creative) with a variable String name;
Then I created another class called Player where I take a name of user.
And main class where I want to save the data kept in Singleton.
The problem is, it saves name of the user only if I take it in main class..it seems not to work in other classes.
What is the reason ? How to fix it?
Thanks for any advice :)
Here's my singleton class:
private String name;
public void setName(String name) {
this.name = name;
}
public String getName( ) {
return
this.name;
}
private static Singleton instance = null;
protected Singleton() {
}
public static Singleton getInstance() {
if(instance == null)
{
instance = new Singleton();
}
return instance;
}
This is a class where I take a name of a user:
public class NewMain {
public NewMain() {
String u_name="agrfd";
Singleton.getInstance().setName(u_name);
}
}
And here is main class where I would like to save all data from Singleton (here I just try to print it to make sure it works):
public class NewMain1 {
public static void main(String[] args) {
Singleton singleton = new Singleton();
System.out.println(singleton.getInstance().getName());
}
}
You are probably using different instances of Singleton design object. Just use Singleton pattern.
Exemplary implementation:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Source
Your usage should be:
public class NewMain1 {
public static void main(String[] args) {
new NewMain(); // execute constructor with setter on creation first
System.out.println(Singleton.getInstance().getName());
}
}
Lets assume we've got base class:
public class Base {
public Base(int i) {
/* ... */
}
/* ... */
}
We want to create singleton based on this class. The problem is that class have public constructor, so extending it will result in singleton having public constructor, too:
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
public SingletonBase(int i) { // Want to avoid this!
super(i)
}
public static void getInstance() {
return _instance;
}
/* ... */
}
Singleton, of course, cannot have public constructors, so we want to avoid this.
So, what is most elegant way/pattern to have proper Singleton with functionalities from class Base?
Edit: Modifying Base class is prohibited, since it is from an external library.
Constructors are not inherited. So just
delete this part and you'll get what you need.
public SingletonBase(int i) { // Want to avoid this!
super(i)
}
Additionally, you may want to make the Base class
abstract so that no one can instantiate it by mistake
by calling the Base constructor directly.
public abstract class Base {
public Base(int i) {
/* ... */
}
/* ... */
}
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
public static SingletonBase getInstance() {
return _instance;
}
/* ... */
}
You could make SingletonBase just a normal subclass and delegate the Singleton-part to a different class.
I don't know what your specific context is, but you would have Subclass extends Base and somewhere else you would have your SingletonContainer or something like that where you have the method public static Subclass getInstance().
That way, you would have your usual inheritance and also the Singleton effect, since the SingletonContainer would be responsible for keeping only a single instance of Subclass.
It is not because you inherit from a class that have a public constructor that you have to create the same public constructor, you can do :
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
public static void getInstance() {
return _instance;
}
/* ... */
}
Or even :
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
private SingletonBase(int i) { // Want to avoid this!
super(i)
}
public static void getInstance() {
return _instance;
}
/* ... */
}