Definition of a singleton pattern
single-case mode ( Singleton pattern) is a relatively simple mode, 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.) )
Common code for single-case mode
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 () {
Hudun Demo
}
}
Advantages of Singleton mode
Because Singleton mode has only one instance in memory, it reduces memory expenditure, especially when an object needs to be frequently
When created, destroyed, and performance is not optimized when 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, when an object's generation requires
When you compare multiple resources, such as reading a configuration and generating other dependent objects, you can create a
Singleton object and then resolve it in a permanent memory-resident way ( The JVM needs attention when using singleton mode in Java EE
garbage collection mechanism).
Singleton mode avoids multiple uses of resources.
Singleton mode allows you to optimize and share resource access by setting global access points on the system.
Disadvantages of a singleton pattern
The singleton mode generally has no interface and is difficult to extend.
The singleton mode is detrimental to the test. In a parallel development environment, if the singleton mode is not completed, it cannot be
tested, there is no interface nor can you use mock to virtual an object.
The singleton pattern conflicts with the single duty principle.
usage Scenarios for single-instance mode
in a system, a class is required to have only one object, and if multiple objects appear, a "bad anti-
should be ", 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, is required throughout the project to
Instead of logging each refresh to the database, use singleton mode to keep the counter value and ensure that it is thread-safe;
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 constants and static methods (such as tool classes) of the environment, you can use the singleton mode (when
can also be directly declared as static).
Considerations for single-instance mode
First, in the case of high concurrency, note the problem of thread synchronization for singleton mode.
second, the replication of objects needs to be considered. In Java, objects cannot be copied by default, if implemented
Cloneable interface, and implements the Clone method, you can create a new object directly by copying the object, object
Replication is not a constructor that calls a class, so even a private constructor, the object can still be copied.
Attention:
A pattern that requires the creation of a fixed number of objects is called an upper-bound multi-case pattern, which is an extension of a singleton pattern.
, we can determine how many instances in memory are available at design time to facilitate system
Extended to fix the possible performance problems of a single case, providing a system response speed.
Definition of the factory method pattern
Factory method patterns are used in very high frequency and can always be seen in our daily development. It is defined as:
Define an interface for creating a object,but let subclasses decide which class to
Instantiate. Factory Method lets a class defer instantiation to subclasses. (Define an interface for creating objects so that subclasses decide which class to instantiate.) The factory method defers the instantiation of a class to its subclasses. )
Advantages of the Factory method model
First of all, good encapsulation, code structure is clear.
Second, the factory method model is very extensible.
Finally, the factory method model is a typical decoupling framework.
Usage scenarios for factory method patterns
first, the factory method pattern is a substitute for the new object, so it can be used where all the objects need to be generated .
Second, when you need a flexible, extensible framework, you might consider using a factory method model.
Again, the factory method pattern can be used in heterogeneous projects.
Finally, it can be used under the framework of test-driven development.
extension of the factory method pattern
1. Reduced to Simple Factory mode
Simple Factory mode ( Simple Factory Pattern), also called
Static Factory mode. In the actual project, the case of adopting this method is more, the disadvantage is that the expansion ratio of factory class
More difficult, does not conform to the opening and shutting principle, but it is still a very practical design pattern.
2. Upgrade to multiple factory classes
3. Alternate Singleton mode
The core requirement of the singleton pattern is that in-memory only one object can be produced in memory by the factory method mode.
4. Deferred initialization
What is deferred initialization ( Lazy initialization)? When an object is consumed, it is not immediately released, factory class
Keep it in its initial state and wait for it to be used again. Lazy initialization is an extended application of the factory method pattern.
Delayed loading of factory classes
public class Productfactory {
private static final map<string,product> Prmap = new HashMap ();
public static synchronized Product createproduct (String type) throws exception{
Product product =null;
If this object is already in the map
if (Prmap.containskey (type)) {
Product = Prmap.get (type);
}else{
if (Type.equals ("Product1")) {
Product = new ConcreteProduct1 ();
}else{
Product = new ConcreteProduct2 ();
Hudun Demo
}
Put objects in the cache container at the same time
Prmap.put (type,product);
}
return product;
}
}
The code is also relatively simple by defining a Map container, which holds all the resulting objects, if the map container has been
The object is returned directly, and if not, an object is produced according to the type required and placed into the Map capacity
To facilitate the next call.
Singleton mode and factory method mode