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;
}
}
Related
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;
...
}
I have a classic singleton implemented in java
public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {} ;
public static ClassicSingleton getInstance() {
if (instance == null)
return new ClassicSingleton();
return instance;
}
}
I have the following driver
public class SingletonDriver {
public static void main(String[] args) {
System.out.println(ClassicSingleton.getInstance().toString());
System.out.println(ClassicSingleton.getInstance().toString());
}
}
The output is something like
ClassicSingleton#75e4f66a
ClassicSingleton#aede59e
I thought the output would be pointing to the same object. Shouldn't the values be the same?
Your implementation of getInstance() is wrong. You never initialize instance, and thus return a new instance on each invocation. If instance is null, you should save it to your data member, and only then return it:
public static ClassicSingleton getInstance() {
if (instance == null)
instance = new ClassicSingleton();
return instance;
}
You forgot to assign new ClassicSingleton() to instance, so you actually have a factory instead of a singleton; you'll create a new instance on every call. (Note also, of course, that this isn't thread-safe.)
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);
}
}
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.