Singleton design pattern series of tutorials - Introduction Principle
A: singleton pattern (the Singleton) learning step
The classic singleton principle:
This article Source: Kaige Java (wx: kaigejava)
Let's look introduce Singleton pattern:
Its focus is to make a class object only one instance of the system. How to understand the Bible?
We understood from the mathematics and logic: Definition singleton is "one and only one" means.
Let's look at a single case will be used to, to understand the significance of what Singleton pattern in place:
For example, the thread pool used to our system, data sources, caches, and hardware and other equipment.
From the thread pool, cache, we can see the significance Singleton pattern: If you have multiple instances create a conflict, based on the result of inconsistencies and other issues to solve this problem, through the summary, you can get one and only one in the system objects on it.
Thinking:
1: Can I use static variables like the way to achieve it?
In fact, from the use of point of view, this approach is also possible.
2: negotiate a global variable is between programmer can do?
To do so, from the use of point of view is also possible.
to sum up:
Singleton; ensure that at most one instance of a class, and provide a global access.
How to set up a singleton class it?
Thinking point:
1: how to make the class not to be arbitrarily constructed?
2: If you can not arbitrarily constructed class, so if you want to use this class how to do?
One problem: We take a look, create a normal class is how to create?
Student studnet = new Student();
Using the new keyword to create. We also know that to create a class using the new keyword, when, in fact, is called the default constructor of the class -> both no-argument constructor.
So, if you want only one class, the constructor of privatization, so you can not use the new keyword that is not use the no-argument constructor to create a class. This ensures that the class will not be created at will.
Question two: If the constructor has been privatized, want to use the class how to do?
Student may be new Student in class () and then outside to provide a public static method to get to.
FIG class to look at the classic single embodiment mode:
All right. This section explains the principle of a single embodiment mode is completed. Next lesson, we use single-mode embodiment of the code by a small example
Kaige personal blog: www.kaigejava.com
Contact Kaige -> public Kaige number: Kaige Java (kaigejava)
This article Kaige blog address: http://kaigejava.com/gwjeesns/article/detail/549