Java design pattern to SingleTon)

Source: Internet
Author: User

This article will give you a detailed introduction of some basic usage from Java design mode to SingleTon mode. If you need to know, you can refer to it.

Type:Creation Design Mode

Intent:Ensure that a class has only one instance and provides a global access point to it.

Applicability:

  • When a class can only have one instance and the customer can access it from a well-known access point
  • When this unique instance should be extensible through subclass, and the customer should be able to use an extended instance without changing the code

Structure:

There are two common methods to implement the SingleTon mode in Java. The first is to write the constructor as private and create a static private object in the class, the getInstance method is used to obtain the object. The second method is to declare a static private variable in the class and get it through the getInstance method, however, you must set this method to thread-safe (with synchronized modified ).

Method 1

The Code is as follows: Copy code
Public class SingleTon {
Private static SingleTon instance = new SingleTon ();
 
Private SingleTon (){

}
 
Public static SingleTon getInstance (){
Return instance;
}
}

Method 2

The Code is as follows: Copy code
Public class Singleton {
 
Private static Singleton instance = null;
 
Public static synchronized Singleton getInstance (){
// You do not need to generate an object every time. The object is created only when it is used for the first time.
// Use the idea of lazy initialization
If (instance = null)
Instance = new Singleton ();
Return instance;
}
}

In general, the first method is safer. The second method is not safe. After all, it cannot be ensured that all Singleton class objects are obtained through the getInstance method. It is possible to directly create an object through Singleton instance = new Singleton.

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.