//single-case mode Public classSingleton {Private StaticSingleton S; PrivateSingleton () {} Public StaticSingleton Getsingleton () {if(s = =NULL) {s=NewSingleton (); } returns; } //Test Public Static voidMain (string[] args) {Singleton s=Singleton.getsingleton (); Singleton S2=Singleton.getsingleton (); System.out.println (S==S2); }}
(As for the pros and cons of the singleton model I'll just copy it!) )
As a kind of design pattern with clear target, simple structure and easy understanding, the single-case pattern is used very frequently in software development and widely used in many application software and frameworks.
1. Key Benefits
The main advantages of the singleton pattern are as follows:
(1) Singleton mode provides controlled access to a unique instance. Because the Singleton class encapsulates its only instance, it can tightly control how and when the customer accesses it.
(2) because there is only one object in the system memory, so the system resources can be saved, for some of the objects need to be created and destroyed frequently the singleton pattern can undoubtedly improve the performance of the system.
(3) Allow a variable number of instances. Based on the singleton pattern, we can extend the method to obtain the specified number of object instances by using a similar approach to single-instance control, which saves system resources and solves the problem that single-instance objects share too much lossy performance.
2. Main disadvantages
The main disadvantages of the singleton pattern are as follows:
(1) Because there is no abstraction layer in the singleton pattern, the expansion of the Singleton class is very difficult.
(2) The duty of the Singleton class is too heavy, which violates the "single duty principle" to a certain extent. Because the Singleton class serves both as a factory role, provides a factory approach, and acts as a product role, it includes business methods that combine the creation of products with the functionality of the product itself.
(3) Many object-oriented languages (such as Java,C #) now have a running environment that provides automatic garbage collection, so if the instantiated shared object is not exploited for a long time, the system will consider it garbage, automatically destroy and recycle the resources, and re-instantiate the next time it is used. This results in the loss of the state of the shared singleton object.
3. Applicable scenarios
You might consider using singleton mode in the following situations:
(1) The system requires only one instance object, such as a system requirement to provide a unique serial number generator or resource manager, or to consider that the resource consumption is too large to allow only one object to be created.
(2) A single instance of the client invocation class allows only one public access point, except for that public access point, which cannot be accessed by other means.
Singleton mode (Java)