简体   繁体   中英

Singleton class return two different singleton objects

I want to design a class which should return a singleton of some third party object. For eg, I want to create a singleton of 3rd party B class object. Below is the design I have made.

public class A{

private static A A = null;
private static B B = null;

private A() {

    B = code to instantiate B Object;

}

public static synchronized A getAInstance() {

    if(A ==null){
        synchronized(A.class){
            if(A == null){
                 A = new A();
            }
        }
    }
    return A;
}
public B getB(){
    return B;
}

}

Can you please help me is this a proper singleton

If I understand your question correctly, you want to have a single instance of a third party class. First of all it is a good practice to access third party obj via wrapper class obj,(clean code handbook of agile software craftsmanship chapter8), in your case class b is wrapped by class a. In order to make a single instance of class b you can just make it an instance variable of class a and then make the class a singleton, code bellow

Public class A{

private static A A = null;
private B B = null;

private A() {
  B = code to instantiate B Object;
 }

public static synchronized A getAInstance() {

if(A ==null){
    synchronized(A.class){
        if(A == null){
             A = new A();
        }
    }
  }
  return A;
 }

public B getB(){
  return B;
 }
}

You can simply have this structure. No explicit synchrnoization required, just leave it to JVM.

public class A {

 private static class BInstanceHolder {
    B BInstance = new B();
}

private A(){}

public static B getB(){

   return BInstanceHolder.BInstance;

}

}

If you only want to have one copy of B, just do it that way! You dont even need a Singleton of Class A. So you could try:

public final class A{

  private A(){}

  private static B instance;

  static{
    instance = code to instantiate B Object
  }

  public static synchronized B getInstance() {
      return B;
  }
}

The static Block will create a instance of B when the Class is first mentioned and will instantiate the instance. The constructor will prevent the A from being made, but you can still access the only instance of B.

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