What are the advantages of using singleton mode in "Go" Java

Source: Internet
Author: User
Tags zend framework

The main purpose of the Java Singleton pattern is to ensure that only one instance of a class is present in a Java application. The advantage of using singleton is that it can save memory because it limits the number of instances and facilitates Java garbage collection (garbage collection).

When we browse BBS, SNS website, often see "current online number" such a content. For such a feature, it is common practice to store the current number of people in a memory, file or database, each time the user logs in, will be immediately removed from memory, file or database, on the basis of 1, as the current number of online display, and then save it back to memory, file or database, so that the subsequent login users see is the updated current number of people online, the same reason, when the user exits, the current number of online work minus 1. So, for such a requirement, we can abstract it into an object of "online counter" according to the object-oriented design idea.

In the site code where the counter is used, as long as the new counter object, then you can get, save, increase or decrease the number of people online. However, the actual use of our code is not good. If more than one user is logged in at the same time, the number of people on the online counter is the same at this point, so they use their respective counters plus 1 to deposit files or databases. The number of users who have been logged in this way is not consistent with the actual number of people online. So, to design this counter as a global object, and everyone sharing the same data, we can avoid similar problems, which is one of the applications of the singleton pattern we are talking about.

Singleton mode guarantees that a class has only a unique instance and provides a global access point.

Can we use a global variable to achieve the requirements of a singleton pattern? We just have to think about it. Global variables do provide a global access point, but it does not prevent others from instantiating multiple objects. The number of objects produced by an external program is bound to increase the management cost and increase the coupling degree between the modules. So, the best solution is to let the class itself be responsible for saving its only instance, and let the class guarantee that it will not produce a second instance, and provide a way for the external object to access the instance. Own things, not by others, this is very consistent with the object-oriented packaging principle.

There are 3 main characteristics of the singleton mode:

1. The Singleton class ensures that there is only one instance of itself.

2, the Singleton class must create its own instance.

3. The Singleton class must provide a unique instance for other objects.

How to implement a singleton pattern: Lazy Singleton and a hungry man single-case classes

There are many ways to implement a singleton pattern, and there are some common lazy-type singleton and a hungry man-type singleton classes. The implementation method we described earlier belongs to the lazy-type singleton class.

· Lazy single-Case class

For the lazy model, we can understand this: the Singleton class is very lazy, only when they need to act, never know how to prepare early. It determines whether an object exists when it is needed, creates an object immediately if it does not, and then returns if an existing object is no longer created and returns immediately.

Lazy mode is created only when an external object requests an instance for the first time.

· A hungry man type single case

For the A hungry man pattern, we can understand this: the Singleton class is very hungry and desperately needs to eat, so it creates the object as soon as the class loads.

Let's compare the pros and cons of lazy mode and a hungry man mode:

Lazy mode, which is characterized by the slow speed at which objects are obtained at runtime, but faster when loading classes. It consumes resources only a fraction of the time throughout the application's life cycle.

A hungry man mode, which is characterized by the slow loading of the class, but the speed at which the object is obtained at runtime is relatively fast. It always consumes resources from the time it is loaded to the end of the app.

These two modes are very quick to initialize, the lightweight object that consumes less resources, there is not much performance difference, choose the lazy or a hungry man-style is no problem. However, for slow initialization, heavy-resource-intensive objects, there will be more obvious differences. Therefore, the A hungry man mode is applied to the heavyweight object, the class loads slowly, but the run time is fast; in contrast to lazy mode, the class loads faster, but the first time the runtime gets the object is slow.

From the user experience point of view, we should prefer a hungry man mode. We are willing to wait for a program to take a long time to initialize, but do not like to wait too long while the program is running, giving people a feeling of insensitivity, so we recommend using a hungry man mode for single-instance mode with heavyweight object participation.

For fast-initializing lightweight objects, you can use either method. If a large number of singleton patterns are used in an application, we should weigh the two methods. The lightweight object's single example uses the lazy mode, reduces the load time, shortens the load times, increases the load efficiency, and because it is a lightweight object, the creation of these objects is put into use, the actual time to create a singleton object is allocated to the entire application, the overall application of the efficiency of the operation is not much impact.

When to use singleton mode

The singleton mode is also a kind of common design pattern, what does it bring to our advantage? In fact, it is nothing more than a three-part function:

First, control the use of resources, through thread synchronization to control the concurrent access of resources;

Second, control the number of instances generated, to achieve the purpose of saving resources.

Third, as a medium of communication, that is, data sharing, it can not establish a direct association under the conditions of a number of unrelated two threads or processes to achieve communication between.

For example, the design of database connection pool is generally based on singleton mode, database connection is a kind of database resource. The use of database connection pool in software system is mainly to save the efficiency loss caused by opening or shutting down the database connection, and the loss of efficiency is very expensive. Of course, there are many other benefits of using database connection pooling, which can block differences between different data databases, achieve low-level coupling of the system to the database, and can be used by multiple systems at the same time, with high reusability, as well as convenient management of database connections and so on. A database connection pool is a heavyweight resource that only needs to be retained in one application, saving resources and facilitating management. So database connection pooling is a very good choice for designing with singleton mode.

In our daily use in Windows There are also many singleton pattern design components, like the common file Manager. Because the Windows operating system is a typical multi-process multithreaded system, when creating or deleting a file, it is inevitable that multiple processes or threads simultaneously manipulate a file. A file manager designed with a singleton pattern can solve this problem perfectly, and all the file operations must be done through a unique instance, so there is no confusion.

For example, each computer can have several printers, and if each process or thread is using the printer resources independently, then the results we print may contain both part of the print task and part of another print task. Therefore, most operating systems end up with a single-mode spool service printer Spooler for print tasks, all of which require a spool service.

In fact, configuration information classes, management classes, control classes, façade classes, and proxy classes are typically designed as singleton classes. Like the struts, spring framework of Java. NET Spring.net framework, and PHP's Zend Framework are heavily used in singleton mode.

For more information, please refer to:

One of the most important aspects of using singleton mode is the principle of "single duty" and "object Autonomy" in object-oriented encapsulation.

Many times we want to make sure that there is only one instance of the class. We may judge in our own code whether an instance of the required class is available or not, and there is no new one. This looks good. The problem is that you use this class in places where there are N, so you need n judgments. Why not give this responsibility to the class itself? Then let the class provide an interface access.

What are the benefits of using singleton mode in

Go Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.