Saturday, 9 March 2013

Doubleton Class in JAVA


Hi Friends....!!
Hi Friends....!!!                             





I would like to share some of my views about Doubleton Class in JAVA.


It’s very similar concept to Singleton Design Pattern.

For any java class if we are allowed to create at-most two objects, such type of class is called as ‘Doubleton class’.

Before going forward, please look into the concepts and implementation of SingletonClass.


Example implementation for the Doubleton class is:

public class Doubleton{
    private static Doubleton objDoubleton1;
    private static Doubleton objDoubleton2;
    private Doubleton(){
    }
    
    // Factory Method
    public  static Doubleton getInstance(){
        if(objDoubleton1 == null){
            objDoubleton1 = new Doubleton();
      return objDoubleton1;
        }
        else if(objDoubleton2 == null){
            objDoubleton2 = new Doubleton();
      return objDoubleton2;
        }
        else{
           if(Math.random() < 0.5)
          return objDoubleton1;
           else
          return objDoubleton2;
        }
    }
    // override clone method
    public  Object clone(){
        return this;
    }
}

Similarly, you can design Tripleton,...., xxxton classes.

5 comments:

  1. Any usage scenario for this doubleton design pattern like any example or overview...

    ReplyDelete
  2. Replies
    1. Math.random will return the value equal to 0.0 or greater than this but less than 1.0.

      Delete
  3. Very useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
    kindle mobi formatting services

    ReplyDelete
  4. public Object clone(){
    return this;
    }
    is clone method has any work with this class doubleton

    ReplyDelete