The Java design pattern--------The singleton pattern for creating patterns

Source: Internet
Author: User
Tags stub

This article is your own study notes, welcome reprint, but please specify the source:http://blog.csdn.net/jesson20121020
  

Singleton mode is also one of the creation modes.

Single-case mode:

The so-called Singleton pattern, a single instance, guarantees that the class has only one object within it.

Example: Windows Print services, network counters

Application: Thread pool, database connection pool, Runtime

  

Before applying the singleton pattern, let's look at an example.

Student.java

public class Student {}

Studenttest.java

public class Studenttest {/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubst udent S1 = new Student (); Student s2 = new Student (); System.out.println (S1 = = s2);}}

This is a simple example of creating a new two student class and judging if the address of the class that created the two is equal in memory, that is, whether the two classes created are the same class in memory.

Obviously, based on the experience of programming, the final output is definitely false, so it essentially creates two classes instead of a class.

While the singleton mode guarantees that there is only one object in memory, and if the class is guaranteed to have only one object in memory, the following steps are given

How do I guarantee that the class has only one object in memory?

1. Privatize the construction method in order not to allow the outside world to create objects

2. Creating an object in a class

3. Provide an entrance to the outside world through a public access approach.

  

By following this step, we can guarantee that the class has only one object in memory, but here's the question: When you create an object in a class in the second step, choose when you want to create the object, or create it when the class loads or when it needs to be created by the outside world?? There are two types of singleton patterns, a hungry man and lazy, respectively, as follows:

Two types of singleton modes:1. A Hungry man type

As the name implies, the object is created when the class is loaded, accessed directly through the Access portal provided in the third step above, without having to be created. The following example:

Student.java

public class Student {//1. In order not to allow outside access, we privatized the construction method private Student () {}//2. Create an object//to satisfy static method access, a static modifier must also be added here. In order not to allow the outside world to modify the S object, you need to privatize s, that is, add the private modifier to the personal private static Student s = new Student ();//3. Provide a public access method//To allow direct access to the outside world, we need to add a static modifier to the method. public static Student Getstudent () {return s;} public void Show () {System.out.println ("I want to learn design mode");}}
Test class:

Studenttest.java

public class Studenttest {/** * @param args */public static void main (string[] args) {//TODO auto-generated method stub// The following essentially creates two classes of/*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, because the construction method of the Student class is privatized, it is not possible to create the class directly through new Student (), but instead to the Student class for the work of creating the class. In order not to allow the outside world to directly modify the student class created in the student class, the created class needs to be privatized as long as it provides a way for the outside world to access the object, that is, the Getstudent () method described above.

In summary, the A hungry man singleton pattern is created when the class is loaded, that is, private static Student s = new Student (); Accordingly, creating objects when required by the outside world is lazy, as follows.
 

2. Lazy Type

Lazy Loading thought: When we need, you will give. (eg. Hibernate)

That is to say, create the object when the outside is needed, and ensure that the class has only one in memory, as in the following example:

Teacher.java

<span style= "FONT-SIZE:12PX;" >public class Teacher {//In order to not allow the outside world to create objects, the method private public Teacher () {//TODO auto-generated constructor stub}//This class creates an object, note that Here can not be new Teacher (), otherwise it becomes a hungry man type//Here add static is to ensure that the static method can access//Here add private is to ensure that the outside world can not directly access the private static Teacher T = null;// Provides public access to the method publicly static Teacher Getteacher () {if (t = = null) T = new Teacher (); return t;} public void Show () {System.out.println ("I want to teach design mode");}} </span>
Test Class

Teachertest.java

<span style= "FONT-SIZE:12PX;" >public class Teachertest {/** * @param args */public static void main (string[] args) {//TODO auto-generated Method St Ubteacher T1 = Teacher.getteacher (); Teacher t2 = Teacher.getteacher (); System.out.println (t1 = = t2); Truet1.show (); T2.show ();}} </span>

   It is easy to see that the Lazy singleton mode not only guarantees that there is only one class in memory, but also creates objects when needed, rather than creating them when the class is loaded, as in the case of a hungry man.

  

After understanding the two types of singleton mode, there is a problem, in the actual development and interview to choose which one???

which singleton mode should be selected in development??

In general, we develop the first method, that is to say a hungry man-style.

Reason:

Multithreading security issues. A hungry man there is no thread-safety problem, and the lazy type has a thread-safety problem.

Specific explanations:

In the A hungry man example, when there are multiple threads accessing, such as T1 and T2 simultaneously accessing getstudent (), because the student object was created when the class was first loaded, they are the same object regardless of who returned it, and are the first objects that have been created. So there is no thread safety issue.

In the lazy example, when there are multiple threads access, such as T1 and T2 simultaneously access getstudent (), this time, when T1 came in to judge this time t=null, so T1 went in to execute if the control of the statement, but notice, due to the randomness of the thread, Maybe T1 just went in to execute if control statement, this time, was T2 grabbed the CPU execution, this time, T2 began to execute, found that this time t is still null, so T2 also go in to execute if the statement of control, then there will be more than one object is created, so lazy type has a thread safety problem.

Therefore, in the development we generally choose the A hungry man-type singleton mode without the thread safety problem.

What kind of singleton mode do you usually choose in an interview?

  In the interview, the general will choose the lazy type Singleton mode, and mainly interview the following several questions:

A: Lazy Loading thought

B: Thread safety issues

A: How is thread safety problem generated??

B: How is the thread safety problem solved??

---Add the Sync keyword "synchronized" where there is a thread safety issue.

Because the code is synchronized, it can only be accessed by one thread at a time.

As a result, the Synchronization keyword "synchronized" can be added to the Getteacher () method to address the thread-safety problem of lazy-type presence.


In fact, in the JDK, there is already a singleton mode of application, is the runtime class, but also the A hungry man-type singleton mode. As follows:

<span style= "FONT-SIZE:12PX;" >public class Runtime {    private static runtime currentruntime = new Runtime ();    public static Runtime GetRuntime () {        return currentruntime;    }    Private Runtime () {}}</span>



  




  


  

The Java design pattern--------The singleton pattern for creating 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.