A single example design pattern of Java learning

Source: Internet
Author: User

Singleton design pattern: Resolves a class that only has one object in memory.

(1) Want to ensure that the object is unique.

A) to avoid excessive creation of such objects by other programs. Prevent other programs from setting up this type of object first

b) Also for other programs to have access to the class object, in this class, you can customize an object.

c) To facilitate the access of other programs to custom objects, you can provide some external access.

(2) How do these three parts show up in code?

A) Privatize the constructor function.

b) Create a class object in the class.

c) provides a way to get to the object.

(3) How to describe things and how to describe them. Add the above three steps when you need to guarantee that the object of the thing is unique in memory.

/* Initialize the object first. Called: a hungry man type. Once the single class is in memory, the object has been created. */class single{private Static Single s = new single ();p rivate single () {}public static single getinstance () {return s;}} The/* object is initialized only when the method is called, also called the object's deferred loading. Called: Lazy try a single class into memory, the object does not exist, only when the GetInstance method is called, the object is established. */class single{private static Single s = Null;private A () {}public static single getinstance () {if (s==null) { Synchronized (Single.class) {if (s==null) s = new single ();}} return s;}}

(4) principle: To define a single case, it is recommended to use a hungry man type.

A single example design pattern of Java learning

Related Article

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.