Singleton pattern (singleton) and starving formula lazy formula

Objective: the entire application has one and only one instance, all references to instances of the type of point to this instance.

Like a country there is only one emperor (XXX), this time everyone called "Emperor" is called XXX refers to himself;

 

Singleton common mode type:

Single starving Example: The object definition directly out

Single lazy Example: given only the variable, not be initialized;

 

My summary:

Starving type, static modification, loaded with the type of load, loss of performance, but the method is relatively simple

Lazy man's  first time with a relatively slow because of the need to load! Thread, unsafe!

 

 

package reviewDemo;

// singleton

 

// hungry Chinese-style, directly to the objects constructed

class SingleDemo{

    private static SingleDemo s1 = new SingleDemo();

    private SingleDemo(){

        // constructor privatization offer, so you can not construct an object outside the!

    }

   

    public static SingleDemo getS1() {

        return s1;

    }

}

 

// lazy type, define, but does not create the object

class SingleDemo2{

    private static SingleDemo2 s3 ;

   

    private SingleDemo2(){

        // constructor privatization offer, so you can not construct an object outside the!

    }

   

    public static SingleDemo2 getS3 () {// This is a method that returns an object is created!

        if(s3 == null){

            s3 = new SingleDemo2();

        } // and the difference between a hungry man-like , at this time only to create an object!

        return s3;

    }

}

 

public class Demo14 {

    public static void main(String[] args) {

        SingleDemo s1 = SingleDemo.getS1();

        SingleDemo s2 = SingleDemo.getS1();

       

        SingleDemo2 s3 = SingleDemo2.getS3();

        SingleDemo2 s4 = SingleDemo2.getS3();

       

        System.out.println(s1 == s2);

        System.out.println(s3 == s4);

       

    }

}

 

Output: true true

 

Note: Enumeration more safer

package reviewDemo;

 

enum Stu{

    jake;

    // constructor will privatize up, reflection can not create an object, security

    private Stu(){

       

    }

}

 

public class Demo15 {

    public static void main(String[] args) {

    }

}

 

Guess you like

Origin www.cnblogs.com/fanweisheng/p/11131558.html