First, the primer
Single-case mode is a model in design mode, in various open source frameworks, applications in the application system, in a few articles in front of me, in conjunction with other modes. Here we have a systematic study on the single sample mode. And analyzed the "Single-Ordered Mode of Samples" in someone.
Second, definition and structure
Single sample mode is also called single mode or single mode. The definition given in the GOF book is: Ensure that a class has only one instance and provides a global access point access to it. "Single Case" in single case mode is often used to represent system components (or resource) that are uniquely unique. For example, file systems, resource manager, etc.
The purpose of single-case mode is to control a particular class only generate an object, and of course, it is also possible to flexibly change the number of objects in a certain situation. So how come to realize the single example mode? The generation of an object of a class is done by a class constructor. If you want to limit the generation of an object, it is necessary to turn the constructor into private (at least protected), so that the outside of the outside cannot generate objects by reference. At the same time, in order to ensure the availability of classes, you must provide a static method of your own object and access to this object.
Now there is a probably understanding of single case mode, in fact, single example mode is very simple - only one role, and customers get class objects by calling class methods.
Put a class diagram, this is more intuitive:
Single sample mode can be divided into stateful and stateless. Some single case objects are typically also variable single-case objects, and multiple single objects can serve as a status repository as a status warehouse. A single case object that is not status is the constant single-case object, only the tool function is used.
Third, realize
There are several different ways in the implementation of single case model, I will explain one by one. Let's take a way, it is called Hungry Chinese in "Java and Mode".
Public class singleton {
// Define one instance in itself inside
// Note this is Private only for internal calls
Private static singleleton instance = new singleleton ();
// As mentioned above, set the constructor to private
Private singleton () {
}
// Static factory method provides a static method for external access to obtain an object public static singleleton getInstance () {return instance;}}}
Below this way is called lazy: P
Public class singleton {
/ / What is the difference between?
Private static singleton instance = null;
/ / Set to private constructor
Private singleton () {
}
// static factory method
Public static synchronized singleton getInstance () {
// This method improves IF (Instance == null) than above
Instance = new singleton (); returnial;
}
}
Let us first compare these two implementations.
First, their constructor is private, completely disconnecting the channel using the constructor to get an instance of the class, but this also makes the class lose polymorphism (probably why someone calls this mode as a single mode ).
In the second method, the static factory method is synchronously processed. The reason is obvious - in order to prevent multiple instances in the multi-threaded environment; there is no such situation in the first mode.
In the second method, the class is delayed to the instantiation to the first time. In the first mode, it is instantiated when the class is loaded, so many additions will be instantiated multiple times. However, since the synchronization processing is used, the reaction speed is slower than the first slow. In the "Java and Mode" book, in the Java language, the first way is more in line with the characteristics of the Java language itself.
The above two implementations have lost polymorphism and are not allowed to be inherited. There is also another flexible point implementation, setting the constructor to protected so that the subclass is allowed to be inherited. In this way, in the specific implementation, it can be re-implemented in the subclass in the parent class in the parent class; or the conditional judgment can be determined in the static method of the parent class; One way to GOF believes is that it is to maintain a registry with an object and a corresponding name (you can use HashMap to implement). The following implementation Reference "Java and Mode" uses a registry.
Import java.util.hashmap;
Public Class Singleton
{
// Used to store correspondence
Private static hashmap sinregistry = new hashmap ();
Static Private Singleton S = New Singleton ();
// Protected constructor
protected singleton ()
{}
Public Static Singleton GetInstance (String Name)
{
IF (Name == Null)
Name = "singleton";
IF (SINREGISTRY.GET (NAME) == NULL)
{
Try {
SinciStry.put (name, class.forname (name) .newinstance ());
} catch (Exception E)
{
E.PrintStackTrace ();
}
}
Return (SINGLETON) (SINRETITON) (SINREGITITRY.GET (Name)
}
Public void test ()
{
System.out.println ("GetClasssuCcess!");
}
}
Public Class SingletonChild1 Extends Singleton
{
Public singletonchild1 () {}
Static Public SingletonChild1 getInstance ()
{
Return (Singletonchild1) Singleton.GetInstance ("SingletonChild1");
}
Public void test ()
{
System.out.println ("getClassSuccess111!");
}
}
The range of constructor of Java is not smaller than the parent class, so there may be an instance of the client to use its constructor.
Fourth, single case mode evil spirits
It may be a bit exaggerating this question, but this is a good warning for beginners. Single sample mode There is a lot of traps and descriptions in Java, which makes it unrecognizable that the single-case model uses limitations, and you have hidden dangers in the system ...
In fact, this issue has been there to come online in the online system as early as 2001. I am just talking here. But for most beginners, it is possible to be very strange. Let me list the traps in Java in Java.
Multiple virtual machines
When the single case class in the system is copied under multiple virtual machines, an instance object can be created under each virtual machine. In a distributed system of EJB, JINI, RMI technology, due to the physical difference between the distributed system in the middle shield, I want to know which single case object is running under the specific virtual machine. It is very difficult. Therefore, in the system of using the above distribution technology, a single case mode in which the presence state should be avoided, because a status of a single case class, on a different virtual machine, the state saved by each single case object is likely to be different, The problem is also produced. And do not use a single case mode in EJB to control access resources because this is responsible for the EJB container. In other distributed systems, when the resources in each virtual machine are different, you can use a single case mode to manage.
Multiple class loaders
When there is a plurality of type loaders loaded, even if they load the same package name, the same class name or even each byte is exactly the same class, which is also taken. Because different class loaders use different namespaces (Namespace) to distinguish the same class. Therefore, a single case class generates multiple single case objects in an environment of multiplexers.
Maybe you think there are not a lot of cases of multiple type loaders. In fact, many types of loaders have a lot of situations. A number of servlet engines are allowed on many J2EE servers, and each engine is using different types of loaders; the applet applet is loaded by the Internet, due to the security factor, the special type loader is used due to safety factors. ,and many more.
In this case, a single case pattern of state will also bring hidden dangers to the system. Therefore, unless the system is coordinated mechanism, do not use a single example mode in the general state.
Error synchronization processing
When using the lazy single case mode described above, the appropriate or not the synchronization processing is also critical. Otherwise, you may not reach the effect of a single object, or may cause an error such as deadlock. Therefore, it must be understood in synchronization when using lazy single case mode. However, this problem can be avoided using the Hungry Han single sample mode.
Subclass destroyed object control
When the last section describes the last extension, it is mentioned that it is possible to lose control of the object because the class constructor is no longer private. This situation can only be specified by a good document.
Serialization (serialized)
In order to make a single case class into a serialized, it is not enough to add "Implements Serializable" in the declaration. Because a serialized object will create a new object when it comes to serialization, not just a reference to the original object. In order to prevent this, the ReadResolve method can be added to a single case class. For details on this method, please refer to Article 57 of the "Effective Java" book.
In fact, the serialization of the object is not only limited to the above manner, but also there is an object serialized method based on XML format. This method also has the above problems, so be careful when using it.
There are some problems that may be encountered in some single-case models. And these problems are intertwined with the basic, threads, virtual machines, etc. in Java, and the complex concepts are intertwined together. If you don't pay a little .... But this does not mean that the single case mode is nothing, and it is more unable to kill it. It is still an indispensable basic design pattern, which provides a very effective solution for some issues. In Java, you can learn it as a coding specification, just use it, you can consider it.
V.
Throw on a single sample mode, use the following simple way to get a single example, and if you are confident that this is always a single case, use the following way maybe better.
Public static final singleton instance = new singleleton ();
The way of using a single example mode, which can change our specific requirements for the single case without changing the API. Six, summary
Do our best to write a detailed introduction of the single example mode, please correct it.