Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the Java singleton model

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to understand the Java singleton pattern". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand the Java singleton pattern".

An overview of design patterns 1.1. The concept of software design patterns

Software design pattern (Software Design Pattern), also known as design pattern, is a set of repeatedly used, known to most people, classified and cataloged, a summary of code design experience. It describes some recurring problems in the process of software design, as well as the solution to the problem. In other words, it is a series of routines to solve specific problems, is a summary of the previous generations of code design experience, has a certain universality, can be used repeatedly. Its purpose is to improve the reusability, readability and reliability of the code.

1.2. The basic elements of software design pattern

1. Pattern name

Each pattern has its own name, which is usually described in one or two words, and can be named according to the problem, characteristics, solution, function, and effect of the pattern. The pattern name (PatternName) helps us understand and remember the pattern, and it is also convenient for us to discuss our own design.

two。 problem

The Problem describes the environment in which the pattern is applied, that is, when the pattern is used. It explains the causes and consequences of design problems and problems, as well as a series of prerequisites that must be met.

3. Solution

The solution to the pattern problem (Solution) includes the components of the design, the relationship between them, and their respective responsibilities and ways of collaboration. Because a pattern is like a template that can be applied to many different situations, the solution does not describe a specific and specific design or implementation. Instead, it provides an abstract description of the design problem and how to solve it with a general combination of elements (a combination of classes or objects).

4. Effect.

This paper describes the application effect of the pattern and the problems that should be weighed when using the pattern, that is, the advantages and disadvantages of the pattern. It is mainly about the measurement of time and space, and the impact of the model on the flexibility, expansibility and portability of the system, as well as its implementation. Explicitly listing these effects (Consequence) is of great help in understanding and evaluating these patterns.

1.3. classification and function of 23 design patterns of GoF

1. Divide according to the purpose

Divided according to what the pattern is used to accomplish.

Creative pattern: used to describe "how to create an object". Its main feature is to "separate the creation and use of the object". GoF provides five creation patterns: singleton, prototype, factory method, abstract factory, and builder.

Structural pattern: used to describe how to form a larger structure of classes or objects according to a certain layout. GoF provides seven structural patterns, such as proxy, adapter, bridge, decoration, appearance, sharing element, combination, and so on.

Behavioral pattern: used to describe how classes or objects work together to accomplish tasks that a single object cannot do alone, and how to assign responsibilities. There are 11 behavioral patterns in GoF, such as template method, policy, command, responsibility chain, state, observer, intermediary, iterator, visitor, memo, interpreter and so on.

2. Functions of 23 design patterns of GoF

Singleton pattern: a class can generate only one instance, and this class provides a global access point for external access to the instance, which extends to a limited number of cases.

Prototype pattern: use an object as a prototype and clone several new instances similar to the prototype by copying it.

Factory method (Factory Method) pattern: defines an interface for creating a product, and the subclass determines what to produce.

Abstract Factory (AbstractFactory) pattern: provides an interface for creating product families, each of which can produce a range of related products.

Builder pattern: decompose a complex object into relatively simple parts, then create them according to different needs, and finally build the complex object.

Proxy mode: provides a proxy for an object to control access to that object. That is, the client accesses the object indirectly through a proxy, thus limiting, enhancing, or modifying some of the object's characteristics.

Adapter mode: converts the interface of one class to another that the customer wants, so that classes that cannot work together because of interface incompatibility can work together.

Bridge pattern: separates abstraction from implementation so that they can change independently. It is realized by using combinatorial relations instead of inheritance relations, thus reducing the coupling degree of the two variable dimensions of abstraction and implementation.

Decorator mode: dynamically adds some responsibilities to the object, that is, to add its additional functionality.

Facade mode: provides a consistent interface for multiple complex subsystems, making them more accessible.

Flyweight pattern: using sharing technology to effectively support the reuse of a large number of fine-grained objects.

Composite mode: combines objects into a tree hierarchy so that users have consistent access to individual and combined objects.

Template method (TemplateMethod) pattern: define an algorithm skeleton in operation, and delay some steps of the algorithm to the subclass, so that the subclass can redefine some specific steps of the algorithm without changing the structure of the algorithm.

Strategy pattern: defines a series of algorithms and encapsulates each algorithm so that they can replace each other, and the changes in the algorithm will not affect the customers who use the algorithm.

Command mode: encapsulates a request into an object, separating the responsibility for issuing the request from the responsibility for executing the request.

Chain of responsibility (Chain of Responsibility) mode: passes a request from one object in the chain to the next until the request is answered. In this way, the coupling between objects is removed.

State mode: allows an object to change its behavior ability when its internal state changes.

Observer mode: there is an one-to-many relationship between multiple objects. When one object changes, the change is notified to other objects, thus affecting the behavior of other objects.

Mediator pattern: define an intermediary object to simplify the interaction between the original objects, reduce the coupling between the objects in the system, so that the original objects do not have to understand each other.

Iterator pattern: provides a way to access a series of data in an aggregate object sequentially without exposing the internal representation of the aggregate object.

Visitor pattern: provides multiple access methods for each element in a collection without changing the collection elements, that is, each element has multiple visitor object access.

Memento mode: get and save the internal state of an object so that it can be restored later without breaking the encapsulation.

Interpreter (Interpreter) pattern: provides how to define the grammar of the language, as well as the interpretation of language sentences, namely the interpreter.

1.4. Seven principles of software design the seven principles of software design describe the opening and closing principle of function to expansion, the principle of opening and closing to modification, reducing the new risk caused by maintenance, the principle of inversion, the principle of dependence on inversion should not rely on the lower level. to program for the interface is more conducive to the upgrade of the code structure, the principle of single responsibility, a class to do only one thing, the implementation class should be single and easy to understand. Improve the readability of code interface isolation principle an interface should do only one thing, interface should simplify single function decoupling, high aggregation, low coupling Demeter rule should not know, a class should maintain the least understanding of other objects, reduce the degree of coupling only communicate with friends, do not talk to strangers, reduce code bloated Richter replacement principle do not destroy the inheritance system, subclass rewriting method function has changed Should not affect the meaning of parent class methods to prevent inheritance from flooding the principle of synthesis reuse try to use composition or aggregation relationships to achieve code reuse and reduce code coupling by using less inheritance

In fact, these principles have only one purpose: to reduce the coupling between objects and to increase the reusability, extensibility and maintainability of the program.

Memory formula: access is restricted, functions should be frugal, dependencies are not allowed, interfaces are dynamically added, parent classes should be abstract, extension should not be changed.

In programming, we should minimize the function of the program and do only one thing per class. If new features are added on the basis of similar functions, inheritance should be used reasonably. For multi-method calls, the interface should be used and the interface function and number should be set reasonably. Finally, low coupling and high cohesion are achieved between classes.

Second, the simple interest model 1.1, the related definition of the singleton model

A pattern in which a class has only one instance and the class can create the instance on its own. For example, only one task manager can be opened in Windows, which avoids the waste of memory resources caused by opening multiple task manager windows, or errors such as inconsistent display of each window.

Three characteristics of simple interest model

A singleton class has only one instance object

The singleton object must be created by the singleton class itself.

The singleton class provides a global access point to the singleton.

Advantages of singleton model

Singleton mode ensures that there is only one instance in memory, reducing memory overhead.

Multiple occupancy of resources can be avoided.

Singleton mode sets global access points to optimize and share access to resources.

Disadvantages of singleton mode:

The singleton mode generally has no interface and is difficult to expand. If you want to expand, there is no second way to violate the principle of opening and closing except to modify the original code.

In concurrent testing, singleton mode is not conducive to code debugging. During debugging, you cannot simulate the generation of a new object if the code in the singleton is not finished.

The functional code of the singleton pattern is usually written in a class, and if the functional design is unreasonable, it is easy to violate the principle of single responsibility.

Application scenario of singleton pattern

For some classes that need to be created frequently, using singletons can reduce the memory pressure of the system and reduce GC.

When only one object is required to be generated, such as the monitor in a class, the ID number of each person, and so on.

Some classes take a lot of resources to create instances, or instantiation takes a long time and is often used.

Some class needs to be instantiated frequently, and the created objects are frequently destroyed, such as multithreaded thread pool, network connection pool, and so on.

Objects that frequently access a database or file.

For some operations that control the hardware level, or should be a single control logic operation on the system, if there are multiple instances, the system will be completely out of order.

When objects need to be shared. Because singleton mode allows only one object to be created, sharing the object can save memory and speed up object access. Such as configuration objects in Web, connection pooling of databases, etc.

1.2. The structure of the simple interest model

Singleton class: a class that contains an instance and can create the instance itself.

Access classes: classes that use singletons.

2.1 the realization of the simple interest model 1: lazy style

The characteristic of this pattern is that no singleton is generated when the class is loaded, which is created only when the getlnstance method is called for the first time.

Code:

Public class LazySingleton {/ / Constructor is private, blocking the possibility of private LazySingleton () {System.out.println ("yese");} / providing objects that outsiders use new to create such objects. It is the only global access point for outsiders to obtain objects of this class. Public static LazySingleton getInstance () {/ / if the object does not exist, new a new object, otherwise return the existing object if (lazySingleton = = null) {lazySingleton = new LazySingleton ();} return lazySingleton;}} @ Test public void testLazy () {LazySingleton L1 = LazySingleton.getInstance () LazySingleton L2 = LazySingleton.getInstance (); System.out.println (L1 + "\ n" + L2); System.out.println (L1 = = L2);}

Test results:

Com.singletonPattern.LazySingleton@78e03bb5

Com.singletonPattern.LazySingleton@78e03bb5

True

This code is obviously not suitable for multithreaded mode, so you need to add a lock to the singleton object.

Class LazySingleton2 {/ / Constructor is private, blocking the possibility of private LazySingleton2 () {System.out.println ("S2");} / providing objects that outsiders use new to create such objects, which is the only global access point for outsiders to obtain objects of this class. Public static LazySingleton2 getInstance () {/ / if the object does not exist, new a new object Otherwise, the existing object if (lazySingleton2 = = null) {synchronized (LazySingleton2.class) {if (lazySingleton2 = = null) {lazySingleton2 = new LazySingleton2 () } return lazySingleton2;}}

There is another problem at this time, that is, when creating an object, you will go through three steps in JVM:

(1) allocate memory space for objects

(2) initialize the object

(3) point the object to the allocated memory space

Well, in the process of executing our multithreaded code, it is possible that he does not follow the order of these three parts, then it will lead to a problem of instruction rearrangement. the way to solve this problem is to add the keyword volatile.

The class LazySingleton3 {/ / constructor is private, blocking the possibility of private LazySingleton3 () {} / / providing objects for the outside world to create such objects using new, and it is the only global access point private volatile static LazySingleton3 lazySingleton3 for the outside world to obtain such objects. Public static LazySingleton3 getInstance () {/ / if the object does not exist, new a new object Otherwise, the existing object if (lazySingleton3 = = null) {synchronized (LazySingleton3.class) {if (lazySingleton3 = = null) {lazySingleton3 = new LazySingleton3 () } return lazySingleton3;}}

Finally, we can also deal with reflection to destroy the simple interest model.

Class LazySingleton4 {/ / provides variables that control reflection public static boolean s = false; / / Constructor private, blocking the possibility that outsiders create such objects using new private LazySingleton4 () {if (s = = false) {/ / when the first object is successfully obtained, the second object cannot get s = true through reflection } else {throw new RuntimeException ("do not break the exception with reflection");}} / / provides the object, which is the only global access point private volatile static LazySingleton4 lazySingleton4 for the outside world to get objects of this class. Public static LazySingleton4 getInstance () {/ / if the object does not exist, new a new object, otherwise return the existing object if (lazySingleton4 = = null) {synchronized (LazySingleton4.class) {if (lazySingleton4 = = null) {lazySingleton4 = new LazySingleton4 ();} return lazySingleton4 }}

The two keywords volatile and synchronized can ensure thread safety, but synchronizing each access will affect performance and consume more resources, which is the disadvantage of lazy singletons.

2.2 the realization of the simple interest model 1: hungry Han style

The characteristic of this pattern is that once the class is loaded, a singleton is created, ensuring that the singleton already exists before the getInstance method is called.

Code:

Public class HungrySingleton {private static final HungrySingleton instance = new HungrySingleton (); private HungrySingleton () {} public static HungrySingleton getInstance () {return instance;}}

The hungry Han singleton has created a static object for the system to use at the same time as the class is created, and it will not be changed in the future, so it is thread-safe and can be directly used for multithreading without problems.

Thank you for your reading, the above is the content of "how to understand the Java singleton pattern". After the study of this article, I believe you have a deeper understanding of how to understand the Java singleton pattern, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report