JAVA design mode -- Singleton mode and java design mode --

Source: Internet
Author: User

JAVA design mode -- Singleton mode and java design mode --

The Singleton mode can be used as a programming technique. Let's talk about the theory and code.

The Singleton mode has three key points:

1) A class can only have one instance

2) the class must create the instance by itself

3) The instance must be provided to the entire system.

Application scenarios:

1) window job manager is a typical Singleton mode. You certainly cannot open two job managers at the same time.

2) The database connection pool technology generally uses the singleton mode, because the database connection is a database resource. The database connection pool is used in the system, mainly to save on opening or closing the database connection.

Efficiency Loss: This kind of efficiency loss is very expensive. It can be greatly reduced by using the singleton mode for maintenance.

3) when developing a configuration file, we generally use the single-instance mode to read the configuration file, because the content in the configuration file is a globally shared resource.

4) the design of multi-threaded thread pool generally also needs to consider the singleton mode. The thread pool can easily control the threads in the pool.

5) The statistical information of the website is generally in the singleton mode. Otherwise, it is difficult to control the website synchronously, for example, count the visits of my blog.

6) We also use the singleton mode to develop the application log function, because we can only append log information to one instance, otherwise it is difficult to control.

Examples:

1) Hungry Chinese Model

How can we understand it? ele. Me, so we have to worry about cooking. Here, when the class is loaded, the class has already created its own instance.

This is also a typical application of space for time. How can this problem be solved? We instantiated this object during class loading, occupying the memory space, but we don't need to instantiate it when using this object,

You can use it directly to save time, that is, to exchange space for time.

Ps: I remember that during the first job interview (when I was in my junior year), the interviewer asked me to cite the typical applications of my project in exchange for space and space for time, ask me the answer.

Code:

Package chc. singleton;/*** hunger singleton mode class * @ author haicheng. cao * @ time 22:4.09.02 */public class EagerSingleton {// The instance object created when the class is loaded-the hunger style (space for time) public static EagerSingleton eagerSingleton = new EagerSingleton ();/*** private constructor displayed to prevent other classes from creating instances of this class */private EagerSingleton () {}/*** static factory method. Other classes call this method to obtain the Instance Object */public static EagerSingleton getEagerSingleton () {return eagerSingleton ;}}

2) lazy Mode

How can this be understood? Lazy, for example, a person starts to write his or her resume only when going to the interview, that is, the object instance is created only when it is used. In this case, there is no creativity during class loading.

Create the instance object of this class, but create it only when other classes are called for the first time.

This is also a typical application that exchanges time for space. That is to say, when classes are loaded, no objects are created, saving memory and space, during the call, you need to determine whether the instance objects of this class are stored.

A waste of time, that is, time in exchange for space.

Code:

Package chc. singleton;/*** lazy singleton mode class * @ author haicheng. cao * @ time 2014.09.02 */public class LazySingleton {// when the class is loaded, it does not create its own instantiated object public static LazySingleton lazySingleton = null; /*** display private constructor to prevent other classes from creating this class instance */private LazySingleton () {}/ *** static factory method, other classes call this method to obtain the instance object of this class */public static synchronized LazySingleton getLazySingleton () {// if (lazySingleton = null) {lazySingleton = new LazySingleton () ;}return lazySingleton ;}}

Note: We add synchronization keywords to the getEasySingleton () method to ensure thread security. But can we improve the program performance by comparing the results? See the following:

3) double check and lock

The double check locking mechanism means that we do not synchronize when calling the getEasySingleton () method. when entering the method, we can determine whether the instance object exists. If not, we are entering the synchronization generation.

Code block. This is the first check. after entering the synchronization block, you can judge whether the instance exists. If there is no instance for this object, this is the second check. In this way, only the first call

After executing a synchronization code block, you do not need to synchronize the rest of the code, improving the program performance.

Code:

Package chc. singleton;/*** double check locks to improve performance in lazy ways * @ author haicheng. cao * @ time 2014.09.02 */public class TwoCheck {private volatile static TwoCheck twoCheck = null; private TwoCheck () {} public static TwoCheck getInstance () {// check whether the instance exists first. if it does not exist, enter the following synchronization block if (twoCheck = null) {// synchronization block, and create the instance synchronized (TwoCheck. class) {// check whether the instance exists again. if it does not exist, create an instance if (twoCheck = null) {twoCheck = new TwoCheck ();}}} return twoCheck ;}}

Q: What is the singleton Design Pattern in Java and what are the advantages?

Singleton mode: ensure that only one instance is available for one class. Advantage is its function. This class will always have only one instance.

Step: 1. Private the construction method of this class;
2. instantiate an instance of this class internally;

3. Provide interfaces for external access.

Public class SingletonDemo {
Private SingletonDemo () {}; // 1.

Private static SingletonDemo mInstance = new SingletonDemo (); // 2.

Public static SingletonDemo getInstance () {// 3.
Return mInstance;

}

}

How to Use the Java Singleton mode?

Public class Singleton {
Private static Singleton sin = new Singleton ();
Private Singleton (){

}
Public static Singleton getInstance (){
Return sin;
}
}
For example, the Class and Runtime classes are all single-column design patterns ..

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.