Construction method Privatization and Singleton mode

Source: Internet
Author: User

One, privatization of construction methods:

That is, the construction method plus the Private keyword.

Such as:

class singleton{    private Singleton () {        //  The construction method is encapsulated, privatized         }};

But because the methods and properties of privatization can only be seen and accessed in this class, other methods are not visible!

So for the following practices.

classsingleton{PrivateSingleton () {//The construction method is encapsulated and privatized    }     Public voidprint () {System.out.println ("Hello World!!!") ; }}; Public classsingletondemo02{ Public Static voidMain (String args[]) {Singleton S1=NULL;//declaring ObjectsS1 =NewSingleton ();//error, could not instantiate object    }};

Operation Result:

Exception in thread "main" java.lang.Error:Unresolved compilation Problem: The     constructor Singleton () was not vis Ible at    Methoud. Thisdemo06.main (Thisdemo06.java:13)

An error occurs and the object cannot be instantiated. The method of structuring privatization is not visible in other classes.

The Singleton class, which is privatized by the constructor method, cannot be instantiated externally.

Since it cannot be instantiated externally, if it is instantiated inside the class

classsingleton{Singleton instance =NewSingleton ();//internally producing instantiated objects of this class    PrivateSingleton () {//The construction method is encapsulated and privatized    }     Public voidprint () {System.out.println ("Hello World!!!") ; }}; Public classsingletondemo04{ Public Static voidMain (String args[]) {Singleton S1=NULL;//declaring Objects    }};

However, although the instantiation object is generated internally, it is not used externally and is assigned to S1. What to do?

The construction method of a class after privatization, you can only get instantiated objects from within the class. So, the question to consider is how to put the internally generated

The instance object is externally accessible so that it can be instantiated directly from the outside.

Under normal circumstances, the instance property can only be called by instantiating an object from the Singleton class.

If you can still get the instance object without instantiating the object, you will need to declare the instance as a static access type, because using the static

Declared variables that can be accessed directly using the class name.

classsingleton{StaticSingleton instance =NewSingleton ();//internally producing instantiated objects of this class    PrivateSingleton () {//The construction method is encapsulated and privatized    }     Public voidprint () {System.out.println ("Hello World!!!") ; }}; Public classsingletondemo04{ Public Static voidMain (String args[]) {Singleton S1=NULL;//declaring Objects        S1 = singleton.instance; Getting instantiated objects from a classS1.print ();//Calling Methods    }};
Run Result: Hello world!!!

By declaring static, the internally generated objects are called through the class name, taken out to the outside, and assigned to S1.

Normally, these attributes should be encapsulated, so the above code is best modified in the following form.

classsingleton{PrivateStaticSingleton instance =NewSingleton ();//internally producing instantiated objects of this class    Public static Singleton getinstance () {//Get instance object return instance by static method; }   PrivateSingleton () {//The construction method is encapsulated and privatized    }     Public voidprint () {System.out.println ("Hello World!!!") ; }}; Public classsingletondemo05{ Public Static voidMain (String args[]) {Singleton S1=NULL;//declaring ObjectsS1 =singleton.getinstance (); Get instantiated ObjectS1.print ();//Calling Methods    }};
Second, the meaning of the procedure:

Why did you do it?

If three objects are now produced.

classsingleton{Private StaticSingleton instance =NewSingleton ();//internally producing instantiated objects of this class     Public StaticSingleton getinstance () {//obtaining instance objects through static methods        returninstance; }    PrivateSingleton () {//The construction method is encapsulated and privatized    }     Public voidprint () {System.out.println ("Hello World!!!") ; }}; Public classsingletondemo05{ Public Static voidMain (String args[]) {Singleton S1=NULL;//declaring ObjectsSingleton s2 =NULL;//declaring ObjectsSingleton s3 =NULL;//declaring ObjectsS1 = Singleton.getinstance ();//get instantiated ObjectS2 = singleton.getinstance ();//get instantiated ObjectS3 = Singleton.getinstance ();//get instantiated ObjectS1.print ();//Calling MethodsS2.print ();//Calling MethodsS3.print ();//Calling Methods    }};

Regardless of how many objects are declared externally, the end result is an instantiated object obtained through the getinstance () method. Other words

At this point S1,s2,s3 actually uses a reference to an object: instance.

In design mode, it is called a singleton design pattern: Singleton.

If you do not want a class to produce too many objects now, you must adopt a singleton design pattern, and, in future Java learning,

This pattern is used extensively in Java-enabled class libraries.

The so-called Singleton is the restriction of the instantiation operation at the entrance (that is, the construction method).

three, a real-world example:

In the window there is a recycle Bin, in addition to the desktop has a recycle Bin, each hard disk has a recycle Bin, in fact, each hard disk on the Recycle Bin and the desktop Recycle Bin is the same,

In other words, the entire operating system has only one instance of the Recycle Bin, and each place simply refers to this instance.

Four, summary

The core of a singleton design pattern is to privatize the constructor of a class, then produce an instantiated object within the class and return a reference to the instantiated object through the static method (static) of the class name reference class.

Construction method Privatization and Singleton mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.