java drawn from within the constructor singleton privatization

Lead to problems

When the constructor for a class of privatization, we can not create a new object in the form of new, to call the object's method. as follows:

class Singleton{
    private Singleton(){
    }
    public void print(){
        System.out.println("hello world");
    }
}

This time we call the print()method, you need the following:

@Test
public void test(){
    Singleton s1 = null;
    s1 = new Singleton();
    s1.print();
}

Program compile time error.

Explore solutions

Since we can not go outside to instantiate an object, then the class is instantiated inside it.

class Singleton{
    Singleton singleton = new Singleton();
    private Singleton(){
    }
    public void print(){
        System.out.println("hello world");
    }
}

The program compile. But the test methods can not throw run, that is to say at this time is focused on how to pass inside to the outside of the singleton object class to go. As mentioned above, marked by the static properties can be accessed directly by the class, the class about the transformation of the above:

class Singleton{
    static Singleton singleton = new Singleton();
    private Singleton(){
    }
    public void print(){
        System.out.println("hello world");
    }
}
@Test
public void test(){
    Singleton s1 = null;
    s1 = Singleton.singleton;
    s1.print();
}

run result:

hello world

But this has its own problems, because we know needs to be encapsulated under the general category of property. But after the package properties, the properties must be obtained by the method, this method must also be declared as static methods.

problem solved

Thus the class becomes as follows:

class Singleton{
    private static Singleton singleton = new Singleton();
    private Singleton(){
    }
    public static Singleton getInstance(){
        return singleton;
    }
    public void print(){
        System.out.println("hello world");
    }
}

test:

@Test
public void test(){
    Singleton s1 = Singleton.getInstance();
    Singleton s2 = Singleton.getInstance();
    Singleton s3 = Singleton.getInstance();

    s1.print();
    s2.print();
    s3.print();
}

result:

hello world
hello world
hello world

Since all classes shared static properties, although we instantiate more than three objects, but they all point to the same reference. That no matter how out of use, the end result is only one instance of the object exists. This mode is called singleton in design mode.

Published 22 original articles · won praise 9 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_19408473/article/details/71171552