Java Fundamentals-Single-row mode of design patterns

Source: Internet
Author: User
Tags volatile

One: Single case design mode

Singleton is a pattern of creation in which a class takes Singleton mode, and when the class is created, it is possible to produce only one instance for external access and a global access point .

Features of the single-case design pattern :

  1. A Singleton class can have only one instance
  2. Singleton must create an object
  3. The Singleton class needs to provide this object externally

The core points of knowledge are as follows :

  1. The construction method of a class with a singleton design pattern is privatized (with private modification).

  2. The instantiated object of the class is produced internally and encapsulated into a private static type.
  3. Defines a static method that returns an instance of the class.

Two: Single-case classification

1. A Hungry man mode:

The advantages are:

  1. It's relatively simple to write.
  2. And there is no multithreading synchronization problem,
  3. Avoid the performance problems caused by synchronized;

The disadvantages are:

  1. When the class is loaded, the static instance is initialized
  2. Static variables are created and allocated memory space, and since then, this static instance object has been occupying this memory (even if you haven't used it yet),
  3. When a class is unloaded, the static variable is destroyed and the occupied memory is freed, so memory is consumed under certain conditions.

 /** * method One * Singleton mode implementation: A Hungry man type, thread safe but low efficiency */public class Singletontest {//define a private construction method private Singletontest () {}/ /set its own instance object to a property, plus the static and final modifiers private static Span style= "COLOR: #0000ff" >final singletontest instance = new  Singletontest ();///static method returns an instance of the class public static Singletontest getinstancei () {return< Span style= "COLOR: #000000" > instance; } } 

2. Full-Chinese style (lazy type)

The advantages are :

  1. It's relatively simple to write.
  2. Static variable instance is not created and allocates memory space when the class is loaded
  3. When the GetInstance method is called for the first time, the instance variable is initialized and memory is allocated, so the memory is saved under certain conditions

The disadvantages are :

  1. Multiple singletontest instances are likely to occur in a concurrent environment.

/*** Method Two * Single-instance mode implementation: Full-Chinese, non-thread-safe **/Publicclass Singletontest {
///define private construction methods (prevent passing new Singletontest () to instantiate) private Singletontest () {}// Define a variable of type singletontest (uninitialized, note that the final keyword is not used here) private Static singletontest instance;//defines a static method (called when the singletontest is initialized, but when multithreaded access is May cause a recurring initialization problem) public static Singletontest getinstance () {if (instance = null) instance = new Singletontest (); return instance;}}

3. Simple and optimized version of method two

The advantage is that multiple instances of the class appear when using the (Sync Lock) synchronized keyword to avoid multi-threaded access. The disadvantage is that when synchronous methods are frequently called, the efficiency is slightly lower.

/*** Method Three * Single-instance mode implementation: Full-Chinese, thread-safe simple implementation **/PublicClasssingletontest {//Define private construction methods (prevent instantiation with new singletontest ())Private Singletontest () {} // Define a variable of type singletontest (uninitialized, note that the final keyword is not used here) private  Static singletontest instance; // Define a static method (initialize Singletontest when invoked, use synchronized Avoid multi-threaded access, which can cause heavy re-initialization problems) public static synchronized Singletontest getinstance () {if ( Instance = = null) instance = new Singletontest (); return instance;}}  
4 optimal implementation of single-case mode
    1. Memory footprint
    2. High efficiency
    3. Thread Safety
    4. Multi-threaded Operation atomicity.

/*** Method Four * Singleton mode optimal scheme * thread safe and high efficiency **/PublicClassSingletontest {//define a private construction methodPrivateSingletontest () {}Defines a static private variable (uninitialized, does not use the final keyword, and volatile guarantees the visibility of the instance variable when multi-threaded access is avoided, and is called by another thread when the other variable property is not assigned when instance initialized)Privatestatic volatile singletontest instance;//defines a common static method that returns an instance of this type public Span style= "COLOR: #0000ff" >static Singletontest getistance () {//or whether the object is instantiated (without using a synchronous block of code, Instance is not equal to NULL, directly returns the object, improving operational efficiency) if (instance = null< Span style= "color: #000000") {//Sync code block (when object is not initialized, use a synchronous block of code to guarantee that the object will not be created again after the first creation of the multi-threaded access)  Classif (instance = null) {instance = new Singletontest (); }}} return instance;}}      

(In fact, the constructor of the private type can be instantiated through the Java reflection mechanism, which essentially invalidates all Java Singleton implementations.) This post does not discuss reflection in the case of problems, default no reflection, is also a common interview has been applied scenario)

Java Fundamentals-Single-row mode of 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.