One of the Java Design Patterns single-instance design patterns

Source: Internet
Author: User

1, what is called design mode:

The concept of design patterns comes first from other industries: the construction industry, in the early days of building a house, it must be inexperienced, appear disorderly, which will cause a lot of problems, in the industry development process, through the accumulation of accumulated experience, the predecessors of these problems put forward a reasonable solution, this is the design model, Referring to design patterns can often solve a lot of problems, in computer programming, there will be similar problems, so the cattle people put these solutions to the problem of classification and summary, the formation of object-oriented programming 23 design patterns.

2. Single case Mode (features):

The singleton schema definition in Java: "A class has and only one instance, and self-instantiation is provided to the system as a whole." " by using design patterns, we can make our code more reusable, more maintainable, and make your code more elegant."

3, motive (the origin of the singleton mode):

1, the first object can look at the physical copy of the class, just like the drawings and drawings created by the entity, the same class of different objects, is the difference in properties, but sometimes we do not need to exist in memory of such multiple objects, such as a system can have only one window manager or file system, such as a task manager that can only be opened in Windows. If you do not use the mechanism to unique window objects, will pop up more than one window, if these windows display exactly the same content, it is a duplicate object, wasting memory resources, if these windows display inconsistent content, it means that in a moment the system has multiple states, and the actual discrepancy, but also to the user misunderstanding, I don't know which one is the real state. So sometimes it is important to ensure that an object in the system is unique, that one class can have only one instance, and that if a software configuration file has multiple users to get configuration information, if it is also creating multiple objects, they manipulate different objects separately, the data cannot be shared in real time, and if memory is an object, You can solve this problem.

2, if the object of a class is likely to be a large number of memory duplication, a certain degree of restrictions on the creation of objects, can reduce memory consumption, of course, this is a more farfetched motive .

4. Ideas (process of problem solving):

To solve the above problem, the first thing to think about is to add static (statically) adornments to the members of the class, which forms the sharing of data, but the main problem here is that static members dwell too long in memory, at least longer than the object, and all the way through a unique object is more appropriate.

    • How to preserve the uniqueness of an object:

1. Do not allow objects of this class to be created (new) in other classes, because it is not possible to control the number of creation.

2, a unique instance of the class must be provided in the class.

3. Provide a method for other classes to obtain the instance.

Specific measures:

1th: You are not allowed to create (new) objects of this class in other classes, because the object creation must call the constructor, so the default constructor is privatized.

2nd: You can create (new) objects of this class in a class.

3rd: Build a method that returns the object of the class.



Code history:

public class Singleton {private Singleton () {};//satisfies 1th public Singleton getinstance () {//seems to meet 2nd return new singleton;// Seems to meet 3rd}}

Question: Why do the 2nd and 3rd plus seem? Think carefully and you'll find the problem:

    1. 2nd, because the class cannot create an object, getinstance () cannot be called;
    2. 3rd, if getinstance () can be called, but each call will create a new object, does not meet the requirements.
Workaround:
    1. The method is statically decorated (static) and called by the class name.
    2. Creates a reference variable for an object, points to the object of the class, and returns a reference to the object in getinstance ().
After modification:
public class Singleton {Singleton instance = new Singleton ();p rivate Singleton () {};p ublic static Singleton getinstance () { return instance;}}
Problem:
    1. Non-static member variables cannot be called in static method getinstance, so it is necessary to turn instance into a static member.
    2. If the first article is established, it is possible to get an instance of the object through Singleton.instance, which is equivalent to calling the GetInstance method, so it is better to add a private modifier to prohibit the method from invoking the object instance.
First, the correct code (a Hungry Man type):
public class Singleton {private static Singleton instance = new Singleton ();p rivate Singleton () {};p ublic static Singleton GetInstance () {return instance;}}

This time we thought mastered the singleton mode, in fact, is mastered, but only a single example of design patterns, such as the "A Hungry man-style", because instance is a static member variable, so the JVM on the class load process, the object is instantiated, so the instance is created in advance.

another way to do this is to create the object when the getinstance is called, which is also called lazy loading or lazy.
Second, lazy-type (lazy loading).
public class Singleton {private static Singleton instance = Null;private Singleton () {};p ublic static Singleton getinstance () {if (instance = = null) {instance = new Singleton ();} return instance;}}

Problem: Lazy writing, there is a problem in multi-threading, that is, create multiple objects, as shown in:
public class Singleton {private static Singleton instance = Null;private Singleton () {};p ublic static Singleton getinstance () {if (instance = = null) {--> a thread enters and hangs. --At this point a B thread enters, this situation causes two threads to execute the new singleton operation, so that there will be more than one class object in memory. Instance = new Singleton ();} return instance;}}

Solution: Add lock.
third, the lazy-type synchronous lock (lazy thread-safe solution).
public class Singleton {private static Singleton instance = Null;private Singleton () {};p ublic static synchronized Singleto n getinstance () {if (instance = = null) {instance = new Singleton ();} return instance;}}

Another way to do this:

public class Singleton {private static Singleton instance = Null;private Singleton () {};p ublic static Singleton getins  Tance () {synchronized (Singleton.class) {///synchronous code block, lock cannot be this, because the method is a static method and cannot get to the this object. if (instance = = null) {instance = new Singleton ();} return instance;}}}

Problem: Locks are judged every time getinstance is called, which reduces the efficiency of the program. Note: the Lock (Singleton.classthe byte-code file object to which the class belongs.

Four, the lazy double-check lock.

public class Singleton {
private static Singleton instance = Null;private Singleton () {};p ublic static  Singleton getinstance () {if (instance = = NULL) {synchronized (Singleton.class) {if (instance = = null) {instance = new Singleton ();} return instance;}}}
Advantage: Only the first call to GetInstance, that is, instance equals null when the lock will be judged, so that the efficiency is raised.

5, the use of single-case mode:
if it is meaningless to create the code just as shown above, the way to use the singleton pattern correctly is to add the code to the original code.

Before adding a singleton mode:

public class Test {public static void main (string[] args) {person P1 = new person ();p 1.setName ("Jack");p 1.setAge (18); person P2 = new Person ();p 2.setName ("David");p 2.setAge (20); System.out.println (P1.getname () + ":" + p1.getage ()); System.out.println (P2.getname () + ":" + p2.getage ());}} Class Person{private string name;p rivate int age;public void SetName (string name) {this.name = name;} Public String GetName () {return name;} public void Setage (int.) {this.age = age;} public int getage () {return age;}}

Operation Result:

Jack:18
David:20

After the singleton mode:

public class Test {public static void main (string[] args) {person P1 = person.getinstance ();p 1.setName ("Jack");p 1.setAge ( 18); person P2 = person.getinstance ();p 2.setName ("David");p 2.setAge (20); System.out.println (P1.getname () + ":" + p1.getage ()); System.out.println (P2.getname () + ":" + p2.getage ());}} Class Person{private String name;p rivate int age;private static Person instance = new Person ()//2. Object in this class to create the class private Pers On () {};//1. Private constructor public static person getinstance () {//3. Creates a method that provides externally the object of the class return instance; public void SetName (String name) {this.name = name;} Public String GetName () {return name;} public void Setage (int.) {this.age = age;} public int getage () {return age;}}

Operation Result:

David:20
David:20

Objective : to ensure the uniqueness of the object

6. Reference:

1, bi-moving teacher's video: javase basic video 08-"04-Object-oriented (singleton design mode-Overview & embodiment). avi", "05-Object-oriented (singleton design mode-memory plot). avi", "06-Object-oriented (singleton design mode-lazy type). avi", Wisdom Podcast Bi Xiangdong Java Basics Video Tutorial-day11-14-multithreading (multithreaded-Singleton design mode-lazy).

2, Baidu Encyclopedia: Single case Mode

3, Stormzhang Blog: design mode of the single case mode, the Android design mode of the single case mode, a few points of view of the singleton mode.


One of the Java Design Patterns single-instance 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.