What are the pros and cons of Singleton and static members?

Source: Internet
Author: User

Opinion one: ( singleton )
The singleton mode has many advantages over static methods:
First, a singleton can inherit a class, implement an interface, and a static class cannot (can integrate classes, but cannot integrate instance members);
Second, the singleton can be delayed initialization, static class generally in the first load is initialized;
Again, the Singleton class can be integrated, and his method can be overwritten;
Finally, perhaps most importantly, a singleton class can be used for polymorphism without forcing the user to assume only the unique instance. For example, you might want to write only one configuration at the beginning, but later you might need to support more than one configuration set, or you might want to allow users to load a configuration object externally from an external file, or write their own. Your code does not need to focus on the global state, so your code will be more flexible.

Opinion two: ( static method )

objects produced in a static method are freed as the static method finishes executing, and the class where the static method resides is not instantiated when static methods in the class are executed. If you are using Singleton, the only instance that is generated will always be in memory and will not be purged by GC (because static attribute variables are not purged by GC) unless the entire JVM exits. I thought about it for a few days, and I wrote the code myself to do an experiment.

Point three: (good! )
because of the DAO initialization, will be compared to the system resources, if the static method to take, will continue to initialize and release, so I personally think that if there is no more complex transaction management, with Singleton will be better. Personal opinion, welcome you master correct.

What are the pros and cons of Singleton and static members?

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.