The so-called Singleton refers to the design mode that is only one instance running in the life cycle of the entire WebApplication. This Singleton mode is typically used in the conditions of external environments and objects. Singleton mode can save Resources, reduce the unnecessary overhead of the system, and thus ultimately improve the performance of the system. You can use two ways to implement Singleton mode, and the commonality is to declare the constructor as private, and provide a public static member (member method or member) Variables) allows customers to access unique entities. The following will specifically introduce these two ways to implement Singleton mode: Ø Method 1: State the public static member as Final form
For example: public class singletonclass {public static final singletonclass instance = new singleletonclass ();
Private kindletonclass () {
}
} Note The above member variable is declared in the final form, which ensures that the SingletonClass instance is constructed, which is always the same instance, and only calls once when the constructor is called with Singletonclass. Instance, so that this method ultimately guarantees the runtime Inside, there is only one example.
Ø Method 2: Use public static factory method to implement Singleton
For example: public class singletonclass {private static final singletonclass instance = new singleletonclass ();
Private kindletonclass () {
}
Public static singleletonclass getInstance () {return instance;}
} This approach can be constructed with the Singletonclass.getInstance () method, which uses the GetInstance method to make a single instance constructor, and declare the constructor as a private form to avoid the construct of the customer from other paths. In us In the actual development process, in many places will be used in a single example mode, such as the reading of the database link Connection, the reading of the configuration file, etc., and many places should use single example mode to avoid too many constructs. Loss in the overall performance of the program