A single example pattern of Zen design Patterns

Source: Internet
Author: User

Reprint: http://www.javaweb1024.com/java/Javajichu/2015/04/09/535.html

Design pattern of Zen First second edition http://www.javaweb1024.com/info/403.jspx

The 7th chapter of the single case model

7.1 I am the emperor, my only one.

Since the Qin Shihuang established the position of the emperor, the same period is basically only one person sitting alone in this position. In this case the subjects are also good to deal with, when we bow down, talk about the emperor, everyone knows who is referring to, rather than in front of the emperor to add a specific name, such as Zhang Emperor, Li Emperor. This process responds to the design field by requiring a class to produce only one object (the emperor), and all objects depend on it for the same reason, because there is only one object that is well known for its temper and habits, and to build a strong and stable relationship, which we have done through the process of the special occupation of the emperor. The emperor every day to receive courtiers, deal with government affairs, courtiers every day to bow to the emperor, the emperor can only have one, that is, a class can only produce an object, how to achieve it? Object generation is done through the New keyword (there are other ways, of course, such as object copying, reflection, etc.), how to control it, but don't forget the constructor, when you create an object using the New keyword, the corresponding constructor is called according to the input parameters. Wouldn't it be possible to disallow externally created objects if we set the constructor to private access? The courtiers bowed down to the only emperor's process class diagram such as

As shown in Figure 7-1.

There are only two classes, Emperor represents the Emperor class, minister represents the courtiers class, and the association to the Emperor class is very simple.

The emperor is shown in Listing 7-1.

Code Listing 7-1 Emperor class

public class Emperor {

private static final Emperor Emperor =new Emperor (); Initialize an emperor

Private Emperor () {

Secular and moral restraint you, the purpose is not to want to produce a second emperor

}

public static Emperor getinstance () {

return emperor;

}

The Emperor spoke.

public static void Say () {

System.out.println ("I am the Emperor xxx ...");

}

}

By defining a constructor for a private access permission to avoid being new to an object by another class, Emperor itself can be a new object, and access to that class by other classes can be obtained by getinstance the same object. The emperor has, the courtiers to appear, its class as shown in Listing 7-2 of the code.

Code Listing 7-2 Courtiers class

Public Class Minister {

public static void Main (string[] args) {

for (int day=0;day<3;day++) {

Emperor emperor=emperor.getinstance ();

Emperor.say ();

}

Three days see the emperor is the same person, honored!

}

}

The results of the operation of the emperor's visit are as follows.

I am the Emperor xxx ....

I am the Emperor xxx ....

I am the Emperor xxx ....

Courtiers every day to see the emperor, today worship the emperor should and yesterday, the day before the same (not considering the transition period, do not find fault OH), the Minister knock over the head, looked up, hi, or yesterday the emperor, old acquaintances, easy to talk, this is a singleton model.

7.2 Definition of a singleton pattern

The singleton pattern (Singleton pattern) is a relatively simple pattern, which is defined as follows:

Ensure a class has a single instance, and provide a global point of access to it. (Make sure that one class has just one instance, and instantiate it yourself and provide this instance to the entire system.) )

The general class of the singleton pattern is shown in Figure 7-2.

Figure 7-2 General class diagram for a single case pattern

The Singleton class is called a singleton class by using the private constructor to ensure that only one instance is produced in an application and is instantiated by itself (using new Singleton () in Singleton). Common source code for a single case pattern

As shown in Listing 7-3.

Code listing 7-3 General code for a singleton pattern

public class Singleton {

private static final Singleton Singleton = new Singleton ();

Restricting the generation of multiple objects

Private Singleton () {

}

Get the instance object by this method

public static Singleton Getsingleton () {

return singleton;

}

Other methods in the class, try to be static

public static void DoSomething () {

}

}

7.3 Application of single case model

Advantages of the 7.3.1 single-case model

Because Singleton mode has only one instance in memory and reduces memory overhead, especially when an object needs to be created, destroyed frequently, and performance is not optimized when it is created or destroyed, the advantages of the singleton pattern are obvious.

Because the singleton pattern generates only one instance, it reduces the performance overhead of the system, and when an object is produced that requires more resources, such as reading the configuration and generating other dependent objects, it can be resolved by directly generating a singleton object when the application starts, and then by permanently residing memory (in Java It is important to note the JVM garbage collection mechanism when using singleton mode in EE.

Singleton mode avoids multiple uses of resources, such as a write file action, because only one instance exists in memory and avoids simultaneous write operations on the same resource file.

Singleton mode can be used to set global access points, optimize and share resource access, for example, you can design a singleton class, responsible for all data table mapping processing.

Disadvantages of 7.3.2 Singleton mode

The singleton mode generally has no interface, the extension is very difficult, to expand, in addition to modify the code basically there is no second way can be achieved. Why can't a singleton mode add an interface? Because an interface has no meaning for singleton schemas, it requires "self-instantiation", and it is impossible to instantiate a single instance, an interface, or an abstract class. Of course, in special cases, the singleton pattern can realize interface, be inherited, etc., need to be judged according to the environment in the system development.

The singleton mode is detrimental to the test. In a parallel development environment, if Singleton mode is not completed, it cannot be tested, and no interface can be used to virtual an object in a mock manner.

The singleton pattern conflicts with the single duty principle. A class should only implement a single logic, not whether it is a singleton, is not a single case depending on the environment, the singleton mode of "want to Singleton" and business logic in a class.

7.3.3 usage Scenarios for single-instance mode

In a system that requires a class to have and only one object, if there are multiple objects there will be "adverse reactions", you can use a singleton mode, the specific scenario is as follows:

An environment that requires a unique serial number to be generated;

A shared access point or shared data, such as a counter on a Web page, can be used throughout the project to keep the value of the counter and ensure thread safety without having to log each refresh to the database, using singleton mode;

Creating an object consumes too much resources, such as accessing resources such as IO and databases;

You need to define a large number of static and static methods (such as tool classes) of the environment, you can use the Singleton mode (of course, can also be directly declared as static way).

7.3.4 Considerations for single-case mode

First, in the case of high concurrency, note the problem of thread synchronization for singleton mode. There are several different implementations of the singleton pattern, and the above example does not produce multiple instances, but the singleton pattern shown in listing 7-4 requires thread synchronization to be considered.

Code Listing 7-4 thread insecure singleton

public class Singleton {

private static Singleton Singleton = null;

Restricting the generation of multiple objects

Private Singleton () {

}

Get the instance object by this method

public static Singleton Getsingleton () {

if (singleton = = null) {

Singleton = new Singleton ();

}

return singleton;

}

}

The singleton mode has no problem in the case of low concurrency, if the system pressure increases, the concurrency increase may occur in memory multiple instances, which destroys the original expectation. Why does this happen? If a thread a executes to Singleton = new Singleton (), but has not yet obtained the object (the object initialization takes time), the second thread B is also executing, execution to (Singleton = = null) judgment, then thread B gets the judging condition is also true, So it goes on, thread A gets an object, thread B Gets an object, and two objects appear in memory!

There are many ways to solve thread insecurity, you can add synchronized keywords before the Getsingleton method, or you can add synchronized to the Getsingleton method, but none of the best singleton patterns It is recommended that the reader use the same method as shown in Listing 7-3 (some books refer to the singleton in Listing 7-3 as the A Hungry Man Singleton, and a single example of synchronized in code listing 7-4 is called a lazy singleton). Second, the replication of objects needs to be considered. In Java, objects are not copied by default, if the Cloneable interface is implemented, and the Clone method is implemented, a new object can be created directly from the object copy, and object replication is not called the constructor of the class, so even if it is a private constructor, the object can still be copied. In general, the case of class replication does not need to be considered, there will be few cases where a singleton class will proactively ask to be replicated, the best way to solve the problem is that the Singleton class does not implement the Cloneable interface.

QQ Group: Focus on Javaweb Development official group (178744906) authentication message: JavaWeb1024

A single example pattern of Zen 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.