Java design mode: GOF Singleton mode; java design mode: gof

Source: Internet
Author: User

Java design mode: GOF Singleton mode; java design mode: gof

I. Singleton)

1. application scenarios of Singleton mode:

① Servlet
② Task Manager
③ Link pool
④ In Spring, each bean is a singleton by default.
⑤ Website counter

2. Requirements for Singleton

① The constructor is private
② Private Static variables
③ Public static methods for accessing private static variables

Conclusion: The result shows that the singleton mode provides a unique object access point for an object-oriented application. No matter what features it implements, the entire application shares an instance object.
II. Implementation of Singleton Mode

1. Hungry Chinese
Thread security, immediate loading, low resource utilization, and high call Efficiency

Package cn.com. zfc. gof01.singleton;

/**
*
* @ Title Singleton01
* @ Describe: Standalone Mode
* @ Author Zhang fuchang
* @ Date 8:40:02 AM, January 1, March 27, 2017
*/
Public class Singleton01 {

// Naturally thread-safe, class loading is to load this instance immediately
Private static Singleton01 instance = new Singleton01 ();

/Constructor privatization
Private Singleton01 (){

}

// The method is not synchronized and the efficiency is relatively high
Public static Singleton01 getInstance (){
Return instance;
}
}



2. Lazy
Thread security, delayed loading, high resource utilization, and low call Efficiency

Package cn.com. zfc. gof01.singleton;

/**
*
* @ Title Singleton02
* @ Describe implementation of the Singleton Mode
* @ Author Zhang fuchang
* @ Date 8:45:42 AM, January 1, March 27, 2017
*/
Public class Singleton02 {

Private static Singleton02 instance = null;

// Construct its privatization
Private Singleton02 (){
}

// Public, synchronous, static
Public static synchronized Singleton02 getInstance (){
If (instance = null ){
Instance = new Singleton02 ();
}
Return instance;
}
}


3. Double search
Thread security, delayed loading, high resource utilization, high call efficiency, but unstable

Package cn.com. zfc. gof01.singleton;

/**
*
* @ Title Singleton03
* @ Describe dual detection lock mode for Singleton mode (not recommended)
* @ Author Zhang fuchang
* @ Date 8:52:59 AM, January 1, March 27, 2017
*/
Public class Singleton03 {

Private static Singleton03 instance = null;

Private Singleton03 (){

}

Public static Singleton03 getInstance (){
If (instance = null ){
Singleton03 SC;
Synchronized (Singleton03.class ){
SC = instance;
If (SC = null ){
Synchronized (Singleton03.class ){
If (SC = null ){
SC = new Singleton03 ();
}
}
Instance = SC;
}
}
}
Return instance;
}

}


4. static internal class (better than lazy class)
Thread security, delayed loading, high resource utilization, and high call Efficiency

Package cn.com. zfc. gof01.singleton;

/**
*
* @ Title Singleton04
* @ Describe static internal class implementation Singleton Mode
* @ Author Zhang fuchang
* @ Date 8:54:40 AM, January 1, March 27, 2017
*/
Public class Singleton04 {

// Privatize the constructor
Private Singleton04 (){

}

// Static internal class
Private static class StaticInnerClass {
Private static final Singleton04 INSTANCE = new Singleton04 ();
}

Public static Singleton04 getInstance (){
Return StaticInnerClass. INSTANCE;
}

}


5. Enumeration Singleton (better than ELE. Me)
Thread security, immediate loading, can naturally prevent reflection and deserialization

Package cn.com. zfc. gof01.singleton;

/**
*
* @ Title Singleton05
* @ Describe: implements the singleton mode in the enumeration mode.
* @ Author Zhang fuchang
* @ Date 9:01:59 AM, January 1, March 27, 2017
*/
Public enum Singleton05 {
// Singleton object
INSTANCE;

// If you want to perform additional operations on the singleton object, add the Method
Public void singlrtonOperation (){

}

}

Iii. test the efficiency of creating Singleton mode in a multi-threaded Environment

Package cn.com. zfc. gof01.singleton. test;

Import java. util. concurrent. CountDownLatch;

Import cn.com. zfc. gof01.singleton. Singleton05;

/**
*
* @ Title SingletonTest
* @ Describe: test the efficiency of creating the singleton mode in a multi-threaded Environment
* @ Author Zhang fuchang
* @ Date 9:24:58 AM, January 1, March 27, 2017
*/
Public class SingletonTest {
Public static void main (String [] args) throws Exception {

Long start = System. currentTimeMillis ();
Int threadNum = 10;
// A synchronization aid that allows one or more threads to wait until
// Set of operations being stored med in other threads completes.
// Counter (1 after a thread completes execution)
Final CountDownLatch countDownLatch = new CountDownLatch (threadNum );

For (int I = 0; I <threadNum; I ++ ){
// Multithreading Test
New Thread (new Runnable (){
@ Override
Public void run (){

For (int I = 0; I <1000000; I ++ ){
// Hunger,
// Object o = Singleton01.getInstance ();
// Lazy, slowest
// Object o = Singleton02.getInstance ();
// Double lock detection, unstable, not recommended
// Object o = Singleton03.getInstance ();
// Static internal class
// Object o = Singleton04.getInstance ();
// Enumeration
Object o = Singleton05.INSTANCE;
}

// Reduce the execution of a thread by 1
CountDownLatch. countDown ();
}
}). Start ();
}

// Blocking
CountDownLatch. await (); // The main thread is blocked until the counter changes to 0!

Long end = System. currentTimeMillis ();
System. out. println ("Total time consumption:" + (end-start ));
}
}

4. What is thread security?

If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe.

In other words, an interface provided by a class or program is an atomic operation for a thread, or switching between multiple threads does not result in ambiguity in the execution result of this interface, that is to say, we don't need to consider synchronization, that is, thread security.

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.