简体   繁体   中英

How to avoid the creation of object in Java?

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

查看Singleton设计模式。

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;
    }
}

As of Java 6 you can singletons with a single-element enum type. This way is currently the best way to implement a singleton in Java 1.6 or later according to tht book "" Effective Java from Joshua Bloch.

package mypackage;
public enum MyEnumSingleton {
INSTANCE;

  // other useful methods here
}

.

"This approach is functionally equivalent to the public field approach,
 except that it is more concise, provides the serialization machinery for free, 
 and provides an ironclad guarantee against multiple instantiation, even in the 
 face of sophisticated serialization or reflection attacks. While this approach 
 has yet to be widely adopted, a single-element enum type is
 the best way to implement a singleton."

Before Java 1.6 a class which should be a singleton can be defined like the following.

public class Singleton {
private static Singleton uniqInstance;

private Singleton() {
}

public static synchronized Singleton getInstance() {
    if (uniqInstance == null) {
        uniqInstance = new Singleton();
    }
    return uniqInstance;
  }
  // other useful methods here
}

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.

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();

    }
}

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.

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.

  1. maintain a static variable in ur object class, incrementing by 1 to the upper limit of objects while creating object
  2. when object > bounds needs to be created, select a random number in range[1,bound] and return that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM