Design Mode -- Singleton design mode and design mode --

Source: Internet
Author: User

Design Mode -- Singleton design mode and design mode --

The design pattern is an effective solution to the problem. It is actually an idea.

 

Singleton design mode:

Solution: ensure that one class can only have one object in the memory. (For example, when multiple programs use the same configuration information object, you must ensure the uniqueness of the object)

How to Ensure uniqueness: 1. Do not allow other programs to use new to create class objects

2. Create an instance of this class in this class

3. provide a method for other programs to obtain the object.

To achieve uniqueness:

1. privatize this type of Constructor (private)

2. Create a class object in this class through new

3. Define a public method to return the created object

Class Single
{
Static Single s = new Single ();
Private Single (){}
Public static Single getInstance ()
{
Return s;
}
}
// The method of calling objects is called by class name. The premise of calling a class name is to call a static method. The content of static access must be static.
Class SingleDemo
{
Single ss1 = Single. getInstance ();
Single ss2 = Single. getInstance ();
System. out. println (ss1 = ss2 );
}
// If the output result is true, the object is unique.

In this way, an object is generated when a class is loaded. It is also known as the tough Singleton mode.

The corresponding lazy format is as follows:

When the class is loaded in, there is no object. The object is created only when the geyInstance method is called. (Delayed Loading Mode)

Class Single2
{
Static Single2 s = null;
Private Single2 (){}
Public static Single2 getInstance ()
{

If (s = null)

S = new Single2 ();

Return s;
}
}

In actual development, there are many hungry Chinese characters, because when the lazy style is used, if a multithreading problem occurs, the uniqueness of the object may cause a security risk. (A lot of interviews are rare)

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.