The use of single case pattern in deep parsing Java design pattern programming _java

Source: Internet
Author: User
Tags garbage collection instance method reflection

Definition: Make sure that a class has only one instance and instantiate it and provide this instance to the entire system.
Type: Creating class Mode
Class Diagram:

Class diagram Knowledge Points:
1. Class diagram is divided into three parts, which is class name, attribute, method
2. To << at the beginning and end of the note information
3. Modifier + on behalf of public,-representing Private, #代表protected, nothing represents the package is visible.
4. The underlined property or method representation is static.
5. Friends unfamiliar with the objects in the class diagram can refer to the article: the relationship of classes in design patterns.
The single case pattern should be the simplest of 23 design patterns. It has the following several elements:

    • Private method of construction
    • private static reference to own instance
    • A static public method that takes its own instance as the return value

Let's look at a simple example:

Package com.wolf.action;
Import Java.util.HashMap;
Import Java.util.Map; public class Demo {public static void main (String args[]) throws Instantiationexception, Illegalaccessexception, class
 notfoundexception {System.out.println (Son.getinstance (). GetName ());
 System.out.println ("Who Am I");
 } class Son extends Father {private String name = "Son";
 Final String CLASS = "Demo";
 Protected String GetName () {return this.query ("AAA"); public static Son getinstance () throws Instantiationexception, Illegalaccessexception, classnotfoundexception {//This
 Must be a global path or you cannot find return (Son) instance ("Com.wolf.action.Son");
 } class Father {private static map<string, object> instance = new hashmap<string, object> ();
 Private String name = "Parent Class";
 protected void Fatcher () {System.out.println ("I am a parent");
 Protected string query (String sql) {return SQL + ' has been done '; public static Object instance (String objname) throws Instantiationexception, IllegalaccessexceptioN, classnotfoundexception {if (Instance.get (objname) = = NULL | |! (
 Instance.get (objname) instanceof Father)) {instance.put (objname, Class.forName (objname). newinstance ());
 Return Instance.get (objname);
 }
}

The single case model is divided into two types according to the timing of the instantiated object: One is a hungry man, one is the lazy single case. The A hungry man singleton instantiates an object to its own reference when the Singleton class is loaded, and the lazy type instantiates the object when it invokes the instance method. The code is as follows:
a hungry man-type single case

public class Singleton { 
  private static Singleton Singleton = new Singleton (); 
  Private Singleton () {} public 
  static Singleton getinstance () {return 
    Singleton; 
  } 
} 

A single example of lazy

public class Singleton { 
  private static Singleton Singleton; 
  Private Singleton () {} public 
   
  static synchronized Singleton getinstance () { 
    if (singleton==null) 
      { Singleton = new Singleton (); 
    } 
    Return singleton 
  } 
} 

Advantages of the single case model:

    • There is only one object in memory that saves memory space.
    • Avoid frequent creation of destruction objects, which can improve performance.
    • Avoid multiple occupancy of shared resources.
    • can be accessed globally.

Applicable scenario: Because of the above advantages of single case mode, it is a more design pattern in programming. I've summed up the scenarios that I know are appropriate for using the single case pattern:

    • Objects that need to be frequently instantiated and then destroyed.
    • Objects that are too time-consuming or too expensive to create, but often used.
    • A stateful tool class object.
    • An object that frequently accesses a database or file.
    • And all the other scenes I've never used to ask for only one object.

Single-Case Mode considerations:

    • You can only use the method provided by a singleton class to get a singleton object, do not use reflection, or you will instantiate a new object.
    • Do not break a single instance class object from a static reference in a class to a dangerous operation.
    • Multithreading uses a single example when using shared resources, attention to thread-safety issues.

Some controversies about the single case pattern in Java:

Objects in a single case pattern are not collected by the JVM garbage collector for a long time?
See a lot of information said: If a single object in memory for a long time, will be considered a garbage by the JVM, in the execution of garbage collection will be cleaned out. The author's opinion is that in the hotspot virtual machine version 1.6, the JVM garbage collector will not reclaim a single Instance object unless it is artificially disconnected from a single instance in a static reference to a single instance object.
For this controversy, the author wrote a separate article for discussion, if you have different views or experience in this field please enter the article single case mode discussion: Single case model and garbage collection to participate in the discussion.

are there multiple single instances in a JVM?
in the case of distributed systems, multiple ClassLoader, and serialization, there is no doubt that multiple single cases will be generated. In the same JVM, will it produce a single example? The getinstance () method provided by using a single example can only get the same single case, unless the reflection is used, and a new one is obtained. The code is as follows

Class C = class.forname (Singleton.class.getName ()); 
Constructor ct = C.getdeclaredconstructor (); 
Ct.setaccessible (true); 
Singleton Singleton = (Singleton) ct.newinstance (); 

In this way, each run produces a new single Instance object. So when using a single case pattern, be careful not to use reflection to generate a new single Instance object.

Lazy single Case thread safe
The main point is that some of the online, lazy single case mode is not safe, even in the method of instantiating the object added synchronized keyword, it is still dangerous, but the author after coding test, found that add synchronized keyword modification, Although it is partially affected by performance, it is thread-safe and does not result in instances where multiple objects are instantiated.

single case mode only a hungry man and lazy two types?
a hungry man and lazy single cases are just two of the more mainstream and commonly used single mode methods, theoretically, any design pattern that can implement a class with only one instance can be called a singleton pattern.

can a single instance class be inherited?
a hungry man and lazy single cases because the construction method is private, they are not inheritable, but many other single example schemas can be inherited, such as a registered single example.

a hungry man-style single case good or lazy single case good
in Java, the A hungry man is superior to the lazy single example. In C + +, lazy single cases are generally used.
The single example pattern is simpler, and there is no example of a code demo here.

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.