Singleton mode of design mode

Original text:

When the singleton mode in the original text is reduced, try it with the code and upload it to GitHub

Key points:

The singleton pattern is a static instance and a private constructor

方法一就是传说的中的饿汉模式优点是:写起来比较简单,而且不存在多线程同步问题,避免了synchronized所造成的性能问题;缺点是:当类SingletonTest被加载的时候,会初始化static的instance,静态变量被创建并分配内存空间,从这以后,这个static的instance对象便一直占着这段内存(即便你还没有用到这个实例),当类被卸载时,静态变量被摧毁,并释放所占有的内存,因此在某些特定条件下会耗费内存。---方法二就是传说的中的饱汉模式优点是:写起来比较简单,当类SingletonTest被加载的时候,静态变量static的instance未被创建并分配内存空间,当getInstance方法第一次被调用时,初始化instance变量,并分配内存,因此在某些特定条件下会节约了内存;缺点是:并发环境下很可能出现多个SingletonTest实例。---方法三为方法二的简单优化优点是:使用synchronized关键字避免多线程访问时,出现多个SingletonTest实例。缺点是:同步方法频繁调用时,效率略低。---方法四为单例模式的最佳实现。操作是将变量private static  Test06FullModuleVolatile sc=null内存占用地,效率高,线程安全,多线程操作原子性。总体来说,单例模式的优缺点如下:

Intent: ensure that a class has only one instance and provide a global access point to access it.

Main solution: a globally used class is frequently created and destroyed.

When to use: when you want to control the number of instances and save system resources.

How to solve it: judge whether the system already has this single instance. If yes, it will be returned. If not, it will be created.

Key code: constructors are private.

Application examples: 1. A party can only have one chairman. 2. Windows is multi process and multi-threaded. When operating a file, it is inevitable that multiple processes or threads operate a file at the same time, so all files must be processed through a unique instance. 3. Some device managers are often designed in singleton mode. For example, a computer has two printers, which must be processed when outputting. Two printers cannot print the same file.

Advantages: 1. There is only one instance in memory, which reduces the overhead of memory, especially frequent creation and destruction of instances (such as the homepage page cache of the school of management). 2. Avoid multiple occupation of resources (such as file writing).

Disadvantages: there is no interface and cannot be inherited, which conflicts with the principle of single responsibility. A class should only care about the internal logic, not how to instantiate it outside.

Usage scenario: 1. It is required to produce a unique serial number. 2. The counters in the web do not need to be added to the database every time they are refreshed, but are cached first with a single instance. 3. Creating an object consumes too many resources, such as the connection between I / O and database.

Note: the getInstance () method needs to use the synchronization lock synchronized (singleton. Class) to prevent multiple threads from entering at the same time, causing the instance to be instantiated multiple times.

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
分享
二维码
< <上一篇
下一篇>>