Singleton pattern analysis of Java design pattern

Singleton mode is the simplest but also very important design mode. Its advantages are as follows:

1. When classes with a large memory footprint need to be created and destroyed frequently, the singleton mode can save memory and improve performance, such as sessionfactory in mybatis

2. When you need to read and write a single file, for example, only one windows text file can be written at the same time, you need to use a single instance to avoid multiple reads and writes

The disadvantages are:

1. Singleton mode has no interface, so it is difficult to expand it.

2. It is not conducive to testing. There is no way to test an object directly according to the interface mock

Finally, its implementation methods mainly include hungry man mode and lazy man mode. The lazy model can be subdivided into several types, which will be discussed later.

Starving mode code:

Lazy mode and thread safe code 1

Lazy mode and thread safe code 2

Conclusion: the beans in the spring container use the singleton mode. The spring container controls the bean life cycle. If the multi instance mode is set, the J2EE container is responsible for the object life cycle.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>