Re singleton - lazy starving

 

Singleton design pattern: solving a class of an object is stored only in memory.

--------------------- object in memory uniqueness -------------------

1. In order to avoid excessive build other programs that class object. To prohibit the establishment of such other program objects;

2. Also other programs in order to allow access to the class object, had a custom object class in the present;

3. In order to allow other programs to access custom objects, can provide some access.

 

How to use the code embodied?

1. constructors privatization;

2. Create a class object in this class;

3. To provide a method of the object can be obtained.

 

For how to describe things, how to describe it

When you need the object when the only thing guaranteed in memory, it will add together the three steps above.

class Demo 
{ 
            Private Demo () {}
             Private  static D = new new Demo ();
             public  static Demo the getInstance () 
            { 
                  return D; 
            }         
} 
// singleton design pattern: the first object is initialized: called: starving formula 

// Objects lazy loading, called the lazy man. Will relate to security issues multithreading, requires locking 
class Demo 
{ 
      Private Demo () {}
       Private  static Demo D = null ;
       public  static Demo the getInstance () 
      { 
            IF (D == null )
            {
                  synchronized( Demo.class )
                 {
                       if(d==null)
                       {
                         d = new Demo();
                       }
                  }
             }
            return d;
       }
}

 

Guess you like

Origin www.cnblogs.com/zxl1010/p/11368188.html