Java Design Pattern -------- creation pattern Singleton pattern

Source: Internet
Author: User

Java Design Pattern -------- creation pattern Singleton pattern

This article is my learning notes, welcome to reprint, but please note the Source: http://blog.csdn.net/jesson20121020
  

The Singleton mode is also one of the Creation modes.

Singleton mode:

The so-called Singleton mode, that is, a single instance, ensures that the class contains only one object.

For example, windows Printing Service and Network counters

Application: thread pool, database connection pool, Runtime

  

Let's look at an example before applying the singleton mode.

Student. java

public class Student {}

StudentTest. java

public class StudentTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubStudent s1 = new Student();Student s2 = new Student();System.out.println(s1 == s2);}}

This example is simple: create two Student classes and determine whether the addresses of the two classes in the memory are equal. That is to say, whether the two classes are the same class in the memory.

Obviously, based on your programming experience, the final output must be false. Therefore, two classes are actually created, not one.

The Singleton mode ensures that there is only one object in the memory, and if the class has only one object in the memory, the following steps are given:

How to ensure that the class has only one object in the memory?

1. privatize the constructor to prevent external users from creating objects

2. Create an object in the class

3. Provide an external portal through a public access method.

  

In this step, we can ensure that the class has only one object in the memory, but there is a problem here, that is, when to choose to create an object in the second step "create an object in the class, do you choose to create a class when loading or when the external needs are met ?? The following two types of Singleton mode are introduced:

Two types of Singleton mode: 1. Hungry Chinese

As the name suggests, an object is created when the class is loaded. During external access, the object is directly accessed through the access portal provided in step 3, without the need to create another object. For example:

Student. java

Public class Student {// 1. to prevent external access, we privatize the constructor private Student () {} // 2. create an object // a static modifier must be added here to satisfy static method access. // In order not to allow the outside world to modify the s object, you need to privatize s, that is, add the private modifier private static Student s = new Student (); // 3. provide a public access method // to allow external access directly, we need to add a static modifier to this method. Public static Student getStudent () {return s;} public void show () {System. out. println ("I want to learn the design mode ");}}
Test class:

StudentTest. java

Public class StudentTest {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stub // two classes are created:/* Student s1 = new Student (); Student s2 = new Student (); System. out. println (s1 = s2); */Student s1 = Student. getStudent (); Student s2 = Student. getStudent (); System. out. println (s1 = s2); s1.show (); s2.show ();}}
After this modification, the Student class constructor is private, so you cannot directly create a class through new Student (). Instead, you can assign the job of creating a class to the Student class, to prevent external users from directly modifying the Student class created in the Student class, you only need to privatize the created class by providing an Access Object method, that is, getStudent () method.

To sum up, the hungry Chinese Singleton mode creates an object when the class is loaded, that is, private static Student s = new Student (); correspondingly, creating an object as needed is a lazy style, as shown below.
 

2. Lazy

Delayed loading thinking: when we need it, you can give it whenever we need it. (Eg. Hibernate)

That is to say, when the outside world needs to create an object and ensure that there is only one class in the memory, as shown in the following example:

Teacher. java

Public class Teacher {// to prevent external objects from being created, create an object in the constructor {// TODO Auto-generated, new Teacher (), otherwise, it becomes a hungry Chinese character. // here, the static method is added to ensure that the static method can be accessed. // here, the private method is added to ensure that the outside world cannot directly access the private static Teacher t = null; // provide the public access method public static Teacher getTeacher () {if (t = null) t = new Teacher (); return t;} public void show () {System. out. println ("I want to teach the design mode ");}}
Test class

TeacherTest. java

public class TeacherTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubTeacher t1 = Teacher.getTeacher();Teacher t2 = Teacher.getTeacher();System.out.println(t1 == t2); //truet1.show();t2.show();}}

It can be easily seen that the lazy Singleton mode not only ensures that there is only one class in the memory, but also creates objects as needed, unlike the hunger style, it is created when the class is loaded.

  

After learning about the two types of Singleton mode, there is a question. Which one should I choose in actual development and interview ???

Which Singleton mode should be selected during development ??

Generally, we adopt the first method in development, that is, the hunger style.

Cause:

Multithreading security issues. There is no thread security problem in the hungry Chinese style, while in the lazy Chinese style there is a thread security problem.

Explanation:

In the case of hunger, when multiple threads access getStudent (), for example, when t1 and t2 access getStudent () at the same time, because Student objects have been created at the beginning of class loading, no matter which one of them returns the same object, they are all created at the beginning, so there is no thread security problem.

In the lazy example, when multiple threads access getStudent () simultaneously, for example, t1 and t2, at this time, when t1 comes in, it is determined that t = null at this time, so t1 goes in to execute the statement controlled by the if statement, but note that due to the randomness of the thread, t1 may just go in and execute the if control statement. At this time, t2 grabbed the cpu execution right. At this time, t2 started to execute and found that t was still null at this time, so t2 also went in and executed the statement controlled by if, in the future, multiple objects will be created, so there will be thread security issues in lazy mode.

Therefore, in development, we generally choose the ELE. Me Singleton mode without thread security issues.

Which Singleton mode will be selected during the interview ??

During the interview, the lazy Singleton mode is generally used, and the following questions are mainly used for the interview:

A: The idea of delayed Loading

B: thread security issues

A: How does thread security problem occur ??

B: How does the thread security problem be solved ??

--- Add the synchronization keyword "synchronized" to the thread security issue ".

Because the code to be synchronized can only be accessed by one thread at a certain time.

Therefore, you can add the synchronization keyword "synchronized" to the getTeacher () method to solve the thread security problems in lazy mode.


In fact, there are already applications in the singleton mode in JDK, that is, the Runtime class, And the ELE. Me Singleton mode. As follows:

public class Runtime {    private static Runtime currentRuntime = new Runtime();    public static Runtime getRuntime() {        return currentRuntime;    }    private Runtime() {}}



  




  


  

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.