Java design pattern--Singleton

Source: Internet
Author: User

Singleton mode can be used as a programming technique, so let's start with the theory that the code

Three key points in a singleton mode:

1), a class can only have one instance

2), the class must create this instance on its own

3), the class must provide this instance to the entire system on its own

Application Scenarios:

1), Window Task Manager is a very typical singleton mode, you certainly cannot open two task manager at the same time

2), database connection pooling technology is generally used in a single case mode. Because a database connection is a database resource. The use of database connection pooling in the system is mainly due to the savings of opening or closing the database connection

Efficiency loss. This loss of efficiency is still very expensive and is maintained in a single-case mode. Can greatly reduce such losses.

3), we in the development of the configuration file read generally also adopt a singleton mode, because the content in the configuration file is a globally shared resource.

4), multi-threaded thread pool design should also consider a single case mode. The thread pool can easily control the thread of the pool.

5), the statistical information of the site. Generally also adopt a single case mode, otherwise difficult to synchronize control. For example, statistics on my blog's number of visits.

6), we develop the application of the log function is also used in the singleton mode, because we can only have an instance to append log information, otherwise bad control.

Several types of patterns in a singleton:

1) A hungry man-mode

How do you understand it, hungry? So we have to be very worried about cooking, which means. When the class is loaded, the class has created its own instance.

This is also a typical application of space exchange time, how to say? We instantiate this object when the class is loaded. It takes up memory space, but we don't have to instantiate it when we use this object.

You can use it directly. It also saves time, which is where space is exchanged for time.


PS: Remember the first job (still in junior time) interview when the interviewer let me cite the project I have done in exchange for space and space for the typical application of time, to me to ask a Meng.

Code:

Package chc.singleton;/** * A hungry man type Singleton mode class * @author Haicheng.cao * @time 2014.09.02 22:40 */public class Eagersingleton {//class loaded It creates its own instance object-The A Hungry man (space for time) public static Eagersingleton eagersingleton=new Eagersingleton ();/** * shows the private constructor method, Prevent other classes from creating instances of this class */private Eagersingleton () {}/** * static Factory method, other classes get the instance object of this class by calling this method */public static Eagersingleton Geteagersingleton () {return Eagersingleton;}}

2) Lazy-mode

How does that make sense? Lazy man, give me a sample. A person will immediately go to the interview to start writing resumes, that is, the object instance to use when the time to create. In this case, when the class is loaded, it does not create a

The instance object of this class is built, but it is created when the other class is first called.

This is also a typical time-for-space application, that is, when classes are loaded without creating objects. Saves memory. That is, it saves space, and when called, it is necessary to infer whether the instance object of this class is stored

In, wasting time, this is the time for space.

Code:

Package chc.singleton;/** * Lazy Singleton mode class * @author Haicheng.cao * @time 2014.09.02 23:05 */public class Lazysingleton {//class loaded The public static Lazysingleton lazysingleton=null;/** * Displays the private construction method without creating a self-instantiated object. Prevent other classes from creating instances of this class */private Lazysingleton () {}/** * static Factory method, other classes get the instance object of this class by calling the method */public static synchronized Lazysingleton Getlazysingleton () {////The first time it is called to create its own instance object if (lazysingleton==null) {lazysingleton=new Lazysingleton ();} return Lazysingleton;}}

Note: We have added a synchronous keyword to the Geteasysingleton () method to ensure thread safety. However, this will affect the performance of the program, can we improve it? Look at the following:

3) Double check plus lock

The double-check locking mechanism means that we are out of sync when invoking the Geteasysingleton () method, and we infer that the instance object exists in the method. Assuming it doesn't exist, we're going into a synchronous generation.

Code blocks. This is the first check, which goes into the synchronization block and then infers that the instance exists, assuming there is no instance of creating the object. This is the second heavy check.

Such It's just the first time I call.

Run a synchronization code block, the rest of the time will not need to synchronize, improve the performance of the program.

Code:

Package chc.singleton;/** * Double check plus lock. For lazy Lifting Performance * @author Haicheng.cao * @time 2014.09.02 22:40 */public class Twocheck {    private volatile static Twocheck t Wocheck = null;        Private Twocheck () {        } public        static Twocheck getinstance () {        //first check if the instance exists, assuming that it does not exist before entering the following synchronization block        if (twocheck = = null) {            //sync block, thread-safe Creation instance            synchronized (twocheck.class) {                //check again if the instance exists, assuming it does not exist to actually create the instance                if (Twocheck = = null) {                Twocheck = new Twocheck ();}}        }        return twocheck;}    }

-------------------------------------the following continuation with 2014.09.03 21:15-----------------------------------------------------

Yesterday, when I was writing this thing, I was struggling with a problem, if there is a part of a globally shared variable, we can declare a static property in the class. The declared properties are then initialized by a static method.

then these static variable can be called in whatever class. Like the following code:

Package Chc.statics;public class Staticdemo {public String logpath=null;public void init () {logpath= "C://log.txt";}}
isn't this code completely an alternative to the singleton?

Today I went to the office to ask the leader. Explain to me very clearly that the way a static variable is declared in a class does enable the functionality of a singleton pattern. However, the above code is the way you need to call when the project starts

Staticdemo class the Init () method. The singleton pattern is to defend oneself completely by oneself, do not need to use external force.

Another situation is that when some global properties are dynamic, the way to static variables requires the program to constantly manipulate the dynamic properties of the class, while static classes can be flexibly controlled by themselves. Lifted

The decoupling of the code The .

Package Chc.singleton;import java.io.*;p ublic class Singleton {public static File file=null;public static long Lastmodifi Ed private static Singleton s=null;private Singleton () {lastmodified=file.lastmodified ();} Public synchronized static Singleton Getsingleton () {//assuming that the value of the variable lastmodified is different from the last time the file was changed, instantiate the IF (S==null & & Lastmodified!=file.lastmodified ()) {s=new Singleton ();} return s;}}
This example is very intuitive. The value of the LastModified in the class is dynamic, assuming that the static block of code is used to maintain it. The program calls the static code once every time the file is changed

once again, the block was initialized To Change the amount of this variable , the single case can be self-flexible maintenance, there is no need for other types of assistance.


-------------------------------------the following continuation with 2014.11.03 20:40-----------------------------------------------------

There is a problem of occupying resources in the A Hungry man type. The lazy type has the thread security question, the following looks a clever writing, the lazy type and the A Hungry man style's merit integrates together. Overcome the lazy and a hungry man-style of the shortcomings.

Package Hirain;import Java.io.bufferedinputstream;import Java.io.fileinputstream;import java.io.IOException;import Java.io.inputstream;import java.util.properties;/** * For deferred loading, thread safety * @author Haicheng.cao */public class AppConfig5 {/   /static inner class is loaded at first use private static class appconfig5holder{private static AppConfig5 instance = new AppConfig5 (); }/** * Defines a method to provide the client with an instance of the AppConfig class * @return An instance of AppConfig */public static AppConfig5 getinstance () {return appconf Ig5holder.instance;} /** * Privatization Construction Method */private AppConfig5 () {//Call the method to read the configuration file Readconfig ();} private string Id;private string Name;public string GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} /** * Read the configuration file, read the contents of the configuration file and set it to the property */private void Readconfig () {Properties P = new properties (); InputStream in = null;try {in = new Bufferedinputstream (New FileInputStream ("Appconfig.properties"));p. Load (in);// Read the contents of the configuration file and set it to the property on this.id = p.getproperty ("id"); this.name = P.getproperty ("name");} catch (IOException e) {System.out.println ("mount config file error, detailed stack information such as the following:"); E.printstacktrace ();} Finally{try {in.close ();} catch (IOException e) {e.printstacktrace ();}}}}
Key point: The use of static internal classes, static internal classes of static variables only when the static internal class is used when the load.


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Java design pattern--Singleton

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.