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;
...
}
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;
}
}
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());
}
}
Can anyone please tell me whether this is a singleton class or not?
public class Final_output{
Cafe_factory obj=null;
private Final_output()
{
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public static void main(String args[])
{
new Final_output();
}
}
Cafe_factory is another class in the same package.
This is not a Singleton.
Singleton for Example is:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Not, it's not. Because you can't create instances of this class outside of it (at least one instance should exist). For the other hand - you can create as many instances inside main as you wish (so it's not singleton either).
Here is an example of Singleton:
public class MySingleton{
private MySingleton(){}
private static InstanceHolder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton getInstance(){
return InstanceHolder.instance;
}
}
Its not.
A singleton has as objective to limit to 1 the number of instances of the same class that can be created, and provide static methods to retrieve this instance.
This is typically done via a private constructor and static methods to retrieve this unique instance. Here neither Final_output nor Cafe_factory respect this contract so none of them use the singleton pattern.
Since you could create n amount of new Cafe_Factory objects in your code also outside the Final_output class, no it is not a singleton. A singleton is never created with the new keyword. Instead, you fetch an instance of it via a static method.
this :
public class Final_output{
private static Cafe_factory obj = null;
private Final_output()
{
obj = getCafeInstance();
}
public static getCafeInstance(){
if(null == obj){
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}else{
return obj;
}
}
}
NO This is not a singleTon
public class Final_output{
private static Final_output ourInstance = new Final_output();
Cafe_factory obj=null;
private Final_output() {
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public Final_output getINstance(){
return ourInstance;
}
}
I am new to java programming,I have one class,for this class i created two object(obj1,obj2).i don't want to create other than these object,if any body wants to create one more object for this class that should refer to first,or second objects only(instead of creating one more object).how to do this?please refer below code
class B
{
void mymethod()
{
System.out.println("B class method");
}
}
class Myclass extends B
{
public static void main(String s[])
{
B obj1=new B();//this is obj1
B obj2=new B();//this is obj1
B obj3=new B();//don't allow to create this and refer this to obj1 or obj2
}
}
Thanks
azam
Check out the Singleton design pattern.
What you need is the Singleton design pattern.
Class B should look something like so:
class B
{
private static B instance = null;
private B()
{
//Do any other initialization here
}
public static B getInstance()
{
if (instance == null)
{
instance = new B();
}
return instance;
}
}
Then, in your Myclass, just do this:
B obj1 = B.getInstance();
B obj2 = B.getInstance();
Note: This is not thread safe. If you are looking for a thread safe solution please consult the Wiki Page.
EDIT: You could also have a static initializer
class B
{
private static B instance = null;
static
{
instance = new B();
}
private B()
{
//Do any other initialization here
}
public static B getInstance()
{
return instance;
}
}
Yeah singleton it seems the correct way consider the info your providing here.
The default singleton implementation would be the following:
public class Singleton {
//holds single instance reference
private static Singleton instance = null;
//private constructor to avoid clients to call new on it
private Singleton()
{}
public static Singleton getInstance()
{
if(null == instance)
{
instance = new Singleton();
}
return instance;
}
}
Now you can get the single instance of the object by calling :
Singleton instance = Singleton.getInstance();
Keep in mind though that if your working on a threaded enviroment, singleton by default is not thread-safe.
You should make the getInstance method synchronized to avoid unexpected returns.
public synchronized static Singleton getInstance()
{
if(null == instance)
{
instance = new Singleton();
}
return instance;
}
Cheers
Generally speaking you need a singleton pattern. You need to make the constructor to become a private method. Then you create a method to instantiate class B, hence class B can only be instantiated by this method. Have a look at the singleton pattern. It is what you want I believe.
create singleton Class, like
public Class A {
private static Class a = new A();
public A getA() {
return a;
}
}
Object of class A has already created in class A itself. You don't need to create it outside. Just use getA() method to retieve the class A's object.
Like :
A objA = A.getA();
This is called Singlton Pattern.
You can use a Singleton. You have 2 possiblilities for that.
1 . Lazy Creation (Here you make the instance when call the function getInstance() and you check if the instance already exists):
class B {
static private B instance;
private void mymethod() {
System.out.println("B class method");
}
static public B getInstance() {
if (instance == null) {
instance = new B();
}
return instance;
}
}
class Myclass extends B {
public static void main(String s[]) {
B obj1 = B.getInstance(); // this is obj1
B obj2 = B.getInstance();
}
}
2 . Eager creation (Here you make the instance when the Class is called for the first time):
class B {
static private B instance = new B();
private void mymethod() {
System.out.println("B class method");
}
static public B getInstance() {
return instance;
}
}
class Myclass extends B {
public static void main(String s[]) {
B obj1 = B.getInstance(); // this is obj1
B obj2 = B.getInstance();
}
}
be aware, that using a singleton is a big restriction to your code. It can be very annoying when it's not possible to instance more than one object.
Especially when you dont have acces to the source....
The Effective way in multi threaded application, the below logic will may help
public class Singleton {
private static volatile Singleton _instance;
private Singleton(){}
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
I suppose people have not understood the problem statement. It says, not more than 2 objects shall be created. Singleton creates a single object and blocks any further instantiation.
maintain a static variable in ur object class, incrementing by 1 to the upper limit of objects while creating object
when object > bounds needs to be created, select a random number in range[1,bound] and return that object.