Java language Implementation-created design pattern-Singleton mode

Source: Internet
Author: User

First, describe

The singleton pattern is to ensure that a class has only one instance object, and that the instance object must be created automatically, that the object's construction method is not provided externally, and that the instance is provided to the entire system. Using singleton mode is equivalent to the entire system sharing the instance object of the class, which is important for concurrent access in Java.

The singleton mode is divided into a hungry man mode and full-han mode, and the A Hungry man mode is to create and initialize the unique instance object of the class when the class is loaded, and the full-Han mode is the time when the system needs to use the instance of this class to create the object.


Ii. advantages and disadvantages of the singleton model

Advantage: In single-column mode, when a client invokes an instance of a class, it can only invoke a common interface, which provides a shared object for the entire system. Because there is only one object in system memory, system resources can be saved, which is undoubtedly more efficient compared to classes that require frequently created and destroyed objects. And by the class itself to control the instantiation process, the class in the process of changing the instantiation has the corresponding scalability.

Disadvantage: A class that implements a singleton pattern cannot be inherited by another class after it has been instantiated, and a class has only one object, so the responsibility of this singleton class is too heavy to a certain extent against the "single responsibility principle"; instances of a class can no longer be changed after initialization and are not suitable for scenarios where instances of classes change frequently If in a distributed system, when a singleton class in a system is copied to a different virtual machine, an instance object is created in each virtual machine, it is difficult to distinguish which single object is running under which virtual machine, and because instances in Singleton mode are a shared concept, Additional code is required to guarantee access security for concurrent access.


third, the source code

Package Tong.yue.day4_25;import java.io.ioexception;/** * Singleton mode is a very common design pattern in which a class can have only one object (instance), typically by privatizing that class's constructor, To prevent the creation of an object of the class outside of the class and provide a unique object to the outside world (this object is created in the Class). * In Java, there are two common modes of implementation, one is a bad Han way, the class of objects with static rest and initialization at the time of class loading; the other is the full-han approach, which is initialized when the object is needed in the program and is not regenerated once it is initialized. * The runtime class in the JDK is actually a singleton pattern, and it's a a hungry man approach. * @author Administrator * */public class Singleton {public static void main (string[] args) {//A hungry man get the object of the Singleton class Singleton_eager s Ingleton = Singleton_eager.getinstance (); Singleton.print ();//A Hungry man gets the object of the Singleton class Singleton_lazy Singleton_lazy = Singleton_ Lazy.getinstance (); Singleton_lazy.print ();}} A hungry man singleton mode, which creates an object when the class is loaded, and then no longer repeats creating class Singleton_eager {//declared as static type, creating an object when the class is loaded private static Singleton_eager Singleton_eager = new Singleton_eager ();p rivate Singleton_eager () {}public static Singleton_eager getinstance () {return Singleton_eager;} public void print () {System.out.println (Singleton_eager);}} Full-Han Singleton mode, when the program first uses the object of the class to create the object, created only once, and then no longer repeatedly created class Singleton_lazy{private static Singleton_lazy Singleton_lazy = The creation of Null;private Singleton_lazy () {}//Singleton objects needs to be synchronized, because access security and consistency are ensured in multithreaded concurrent access. Public synchronized static Singleton_lazy getinstance () {//If you use the object for the first time, create one, or use an already created object if (singleton_lazy== NULL) {Singleton_lazy = new Singleton_lazy ();} return singleton_lazy;} public void print () {System.out.println (Singleton_lazy);}}
Operation Result:


Iv. Summary

The constructors and public methods of both scenarios are static (static), and the class instance is shared. It's just that the A hungry man has created the object at the time the class was loaded, and it doesn't have to be created each time it is called, but it returns the created instance directly. This saves time, but takes up space, and the instance itself is static and will always reside in memory.

The lazy type does not create the object when the class is loaded, but only once when the program uses the object of the class, and every time the instance object is used, it is judged whether it exists, and if it exists, it does not exist, which will inevitably affect the speed at which the program runs. Most crucially, in the case of concurrency, lazy-type is unsafe if two threads : thread 1 and thread 2, call the GetInstance () method at the same time, if the thread 1 advanced into The IF statement just to judge that the object is not there, When the object is ready to be created , the thread switches, and then thread 2 controls that the If statement is created without objects, then two instances are created , so the lazy singleton mode getinstance () the Synchronized method is added to the synchronization control to ensure the security of concurrent access.


Java language Implementation-created design pattern-Singleton mode

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.