Java design mode: Singleton Design Mode

Source: Internet
Author: User

Java design mode: Singleton Design Mode

1. What is the design model:

The concept of the design model first comes from other industries: when building a house in the construction industry in the early stages, there must be a lack of experience and disorder. This will cause many problems in the development process of the industry, through continuous experience accumulation, our predecessors have put forward reasonable solutions to these problems. This is the design mode, which can solve many problems by referring to the design mode. In terms of computer programming, similar problems may also occur, so Niu people classify and summarize these solutions to Form 23 design patterns for object-oriented programming.

2. Singleton mode (features ):

Java single-instance mode definition: "A class has only one instance and is self-instantiated to provide to the entire system ." By using the design pattern, we can make our code more reusable, more maintainability, and more elegant in writing your code.

3. motivation (the origins of Singleton mode ):

1. First, the object can look at the physical copy of the class, just like the object created by the drawing and the drawing. Different objects of the same class are attribute differences, but sometimes we do not need to have multiple objects in the class in the memory. For example, a system can only have one window manager or file system. For example, in Windows, only one task manager can be opened. If you do not use the window object uniqueness mechanism, multiple windows will pop up. If the content displayed in these windows is completely consistent, it is a duplicate object, wasting memory resources; if the content displayed in these windows is inconsistent, it means that the system has multiple States at a certain moment, which is inconsistent with the actual status. It may also cause misunderstandings to the user, and the user does not know which one is the real status. Therefore, it is important to ensure the uniqueness of an object in the system. For example, when multiple users in the software configuration file obtain configuration information, if multiple objects are created, they operate on different objects separately, and data cannot be shared in real time. If the memory is an object, this problem can be solved.

2. If a class object may limit the creation of an object to some extent when a large number of memory repetitions occur, the memory consumption can be reduced. Of course, this is a relatively far-fetched motive.

4. Ideas (Problem Solving Process ):

To solve the above problem, the first thought is to add static (static) modifier to the class members, thus forming data sharing, however, the main problem exists here is that the residence of static members in the memory is too long, at least longer than the object, and it is more suitable for all methods that use unique objects.

 

How to Ensure the uniqueness of objects:

 

1. You are not allowed to create (new) objects in other classes because the number of objects created cannot be controlled.

2. A unique instance of this class must be provided in this class.

3. Provide an external method so that other classes can obtain the instance.

Specific Method:

First: do not allow other classes to create (new) class objects, because the object creation must call the constructor, so the default constructor is private.

Second, you can create (new) objects in the class.

Third: Construct a method that returns the object of this class.

Code history:

Public class Singleton {private Singleton () {}; // satisfies the first point: public Singleton getInstance () {// It seems to satisfy the second point: return new Singleton; // It seems to satisfy the third point }}

Q: Why does it seem like adding the second and third points? When you think about it, you will find the problem:

In point 2, because this class cannot create objects, getInstance () cannot be called. In point 3, if getInstance () can be called, a new object is created for each call, does not meet the requirements. Solution: Add static modifier to the method and call it by class name. Create an object reference variable pointing to the object of this class and return the object reference in getInstance. After modification:
public class Singleton {Singleton instance = new Singleton();private Singleton(){};public static Singleton getInstance(){return instance;}}
Problem: In the static method getInstance, non-static member variables cannot be called, so you need to change the instance to a static member. If the first rule is true, you can use Singleton. instance to obtain the instance of the object, which is equivalent to calling the getInstance method. Therefore, you are advised to add a private modifier to prohibit this method from calling the object instance. I. correct code (hungry Chinese Style ):
public class Singleton {private static Singleton instance = new Singleton();private Singleton(){};public static Singleton getInstance(){return instance;}}

At this time, we thought we were able to master the singleton mode, but it was just a way of writing the singleton design mode. because the instance is a static member variable, during the jvm loading of this class, the object is instantiated, so the instance is created in advance.

Another method is to create an object only when getInstance is called. This method is also called "delayed loading" or "lazy loading". 2. Lazy (delayed loading ).
public class Singleton {private static Singleton instance = null;private Singleton(){};public static Singleton getInstance(){if(instance == null){instance = new Singleton();}return instance;}}
Problem: the lazy way of writing may cause problems in multithreading, that is, creating multiple objects, as shown in:
Public class Singleton {private static Singleton instance = null; private Singleton () {}; public static Singleton getInstance () {if (instance = null) {--> A thread A enters and suspends. --> At this time, a line B enters. In this case, both threads will execute the new Singleton operation, so that multiple class objects exist in the memory. Instance = new Singleton ();} return instance ;}}

Solution: Lock. Iii. Lazy synchronization lock (solution for loose thread security ).
public class Singleton {private static Singleton instance = null;private Singleton(){};public static synchronized Singleton getInstance(){if(instance == null){instance = new Singleton();}return instance;}}

Another method:

Public class Singleton {private static Singleton instance = null; private Singleton () {}; public static Singleton getInstance () {synchronized (Singleton. class) {// Synchronous Code block. The lock cannot be this because this method is a static method and cannot obtain this object. If (instance = null) {instance = new Singleton () ;}return instance ;}}}
Problem: the lock is determined every time getInstance is called, which will reduce the program efficiency. Note: The bytecode file object to which the lock (Singleton. class) belongs.

4. Lazy double check lock.

public class Singleton {
private static Singleton instance = null;private Singleton(){};public static  Singleton getInstance(){if(instance == null){synchronized(Singleton.class){ if(instance == null){instance = new Singleton();}return instance;}}}}
Advantage: the lock is determined only when getInstance is called for the first time, that is, when instance is equal to null. This improves the efficiency. 5. Use of Singleton mode:It makes no sense to create the code just as shown above. The correct way to use the singleton mode is to add the code to the original code.

Before adding the singleton mode:

 

public class Test {public static void main(String[] args){Person p1 = new Person();p1.setName("Jack");p1.setAge(18) ;Person p2 = new Person();p2.setName("David");p2.setAge(20);System.out.println(p1.getName() + ":" + p1.getAge());System.out.println(p2.getName() + ":" + p2.getAge());}}class Person{private String name ;private int age;public void setName(String name){this.name = name;}public String getName(){return name;}public void setAge(int age){this.age = age;}public int getAge(){return age;}}

Running result:

Jack: 18
David: 20

After Singleton mode:

Public class Test {public static void main (String [] args) {Person p1 = Person. getInstance (); p1.setName ("Jack"); p1.setAge (18); Person p2 = Person. getInstance (); p2.setName ("David"); p2.setAge (20); System. out. println (p1.getName () + ":" + p1.getAge (); System. out. println (p2.getName () + ":" + p2.getAge () ;}} class Person {private String name; private int age; private static Person instance = new Person (); // 2. private Person () {}; // 1. private constructor public static Person getInstance () {// 3. create a method to provide the return instance;} public void setName (String name) {this. name = name;} public String getName () {return name;} public void setAge (int age) {this. age = age ;}public int getAge () {return age ;}}

Running result:

David: 20
David: 20

Purpose:Ensures the uniqueness of objects.

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.