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

A brief introduction to singleton pattern in java Design pattern

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "A brief introduction to the singleton pattern in the java design pattern". In the daily operation, I believe that many people have doubts about the simple introduction of the singleton pattern in the java design pattern. The editor consulted all kinds of data and sorted out the simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about the "simple introduction to the singleton pattern in the java design pattern". Next, please follow the editor to study!

I. introduction

What is the singleton pattern? Therefore, the name Siyi means to write alone. Yes, it is to ensure that there is only one object from beginning to end in the whole system. For example, our cutest school can have many students and directors, but not many principals. Why? To ensure that there is only one principal, the school system will not collapse because of interference, so the singleton model arises at the historic moment.

Second, the mode of realization

Now that we know what the singleton model is, it's easy to do. First of all, you need to make sure that Lao Wang has only one object in the laowang class of the whole system. What are you going to do? It is conceivable that Lao Wang cannot be created by other kinds.

Therefore, there are the following practices:

1. First, the constructor is private.

two。 Then create an object and put it in memory while the program is running.

You read it correctly, to achieve the singleton model, there are really only two steps, the first step is done in 2 seconds, and the second step is the part we are going to discuss.

There are five ways to implement the singleton pattern:

Hungry Han style:

That is, the object is created in advance when the program is loaded, and someone comes and gives it to him.

Lazy style:

Create the first object when someone needs it, and then give it to him. (lazy load)

Double inspection method:

Inner class mode:

Enumeration method:

Tip: only thread-safe practices are shown in the above implementation, which I will point out later.

III. Concrete realization

1. Hungry Han style

It is divided into two steps:

Privatize the construction method

Create an instance in advance when the program is loaded

Class Laowang {

Private Laowang () {} / / privatization construction method

Private static Laowang laowang=new Laowang (); / / create a static instance directly

/ / provide static methods to obtain the current Laowang

Public static Laowang getLaowang () {

Return laowang

}

}

/ / Main method

Public static void main (String [] args) {

/ / use the static method getLaowang () of the Laowang class to get the instance

Laowang laowang1=Laowang.getLaowang ()

Laowang laowang2=Laowang.getLaowang ()

/ / determine whether laowang1 and Lao Wang 2 are the same object (output true, otherwise false)

System.out.println (laowang1==laowang2)

}

Running result: true

In the above example, in Lao Wang's class, we first privatize the constructor, then create a static property laowang, and then provide an external static method getLaowang () to get the laowang for others. (because you have privatized the constructor, you can only give the laowang to others statically.)

Two reference laowang1,laowang2 are defined in the Main method, but both get the instance object laowang. Exe in the same way. So you get the same object, so return true, which is the hungry Chinese implementation.

Advantages: easy to implement and thread safe.

Cons: obviously, it is created directly when the class is loaded, and sometimes you don't need it, it will also be created, resulting in a waste of memory resources.

There is another way to write the hungry Han style, which has the same effect. Put new Laowang () in a static code block, as follows:

Class Laowang {

Private static Laowang laowang

Private Laowang () {} / / privatization construction method

Static {

Laowang=new Laowang ()

}

/ / provide static methods to obtain the current Laowang

Public static Laowang getLaowang () {

Return laowang

}

}

two。 Lazy style

Give it to the program only when it needs to be called (lazy load), so do the following:

Class Laowang {

Private static Laowang laowang

Private Laowang () {} / / privatization construction method

/ / provide static methods to the outside world, create an instance and return the current Laowang

Public static synchronized Laowang getLaowang () {

If (laowang = = null) {

Laowang=new Laowang ()

}

Return laowang

}

}

This requires adding synchronized to the method declaration (specific role: for example, many people have to queue up to access this method). That is to say, when someone needs to use laowang, call getLaowang (), first wait in line, wait for him, go in to determine whether the laowang is empty, it is only new, do not just give him the current laowang. Of course, the running result of main is still true, which is not described here.

Advantages: no memory waste

Disadvantages: obviously, everyone is equal, everyone has to queue up, since the queue is slow, high concurrency, extremely affect efficiency.

Explain why synchronization locks are added here: if not, for example, at the beginning of the program, Xiaohei and Xiaohong visit this method at the same time, and they must be judged to be empty at the same time, and both of them are inside, new Laowang (); it is obvious that laowang is not a single case. So it needs to be locked. Xiao Hei and Xiao Hong have to wait in line.

3. Double check lock

Also belongs to lazy loading.

Class Laowang {which abortion hospital in Zhengzhou is good for http://www.csyhjlyy.com/

Private volatile static Laowang laowang;// must add the volatile keyword

Private Laowang () {} / / privatization construction method

/ / provide static methods to the outside world, create an instance and return the current Laowang

Public static Laowang getLaowang () {

If (laowang = = null) {

Synchronized (Laowang.class) {/ / synchronization code (still queued)

If (laowang==null) {

Laowang=new Laowang ()

}

}

}

Return laowang

}

}

Analysis of the code ha, the first static attribute laowang to add volatile (specific role to learn more about the words suggest Baidu search ha, is a part of multi-threaded content). Then in the getLaowang () method, first determine whether the laowang is empty, and if so, please queue up. After the queue, judge again, if it is still empty, only new a return.

Give an example of why you should do this:

Or Xiaohei Xiaohong, come in concurrently to visit at the same time, and then must be judged to be empty for the first time at the same time, then two people line up, Blackie goes in to play for a while, and must be judged to be empty for the second time. As a result, Xiaohei new must have left a laowang. Line up to Xiao Hong, Xiao Hong came in for the second time and found that laowang was not empty, so she took it away directly.

Warm Tip: watch again and then continue to read the following

At this time, someone asked, why do you judge for the first time? isn't it fragrant to wait in line directly? Yes, this is what I don't understand for the first time. Our brain circuit goes back to Xiao Heigang's new and laowang is gone. I was just about to wait for Xiao Hong. All of a sudden, there is a third mistress, if you do not judge for the first time, the mistress will continue to rank behind Xiao Hong, resulting in reduced efficiency. But now, for the first time, the mistress found that laowang was no longer empty (at this time, laowang was made by Xiao Hei, the first person), so she took it directly.

Advantages: it solves the problem of low queuing efficiency and thread safety.

Disadvantages: the implementation is more complex.

4. Internal class mode

Also belongs to lazy loading, hence the name Siyi, first of all, the whole internal class comes out, the code is as follows:

Brother, if you want to see the following code, please first understand the function of the final keyword

Here is a brief description of final:

Use for a class: indicates that the class cannot be inherited (commonly known as a severed grandchild class)

Use for a method: indicates that the method cannot be overridden

Use for basic types: for example, int,float … Indicates that the value cannot be changed

Use for reference objects: indicates that the reference points to only one object from beginning to end

Above 3. Use for basic types, 4. The use of reference objects must be directly assigned.

Class Laowang {

Private Laowang () {} / / privatization construction method

/ / provide static methods to the outside, call the properties of the inner class, and return

Public static final Laowang getLaowang () {

Return laowangHolder.INSTANCE

}

/ / static inner class

Private static final class LaowangHolder {

Private static final Laowang INSTANCE = new Laowang ()

}

}

Explain the above code: first declare an inner class (LaowangHolder), which has a static and final-modified property INSTANCE, so you need to assign a value directly, new Laowang (); then call the INSTANCE property of the inner class in the getLaowang () method and return. Because INSTANCE is modified by final and only points to the same laowang, it is a singleton.

5. Enumeration mode

These methods are relatively easy to implement, so go straight to the code:

Enum Laowang {

Laowang

Public void whateverMethod () {}

}

/ / Main method:

Public static void main (String [] args) {

/ / just call it as an attribute

Laowang laowang1=Laowang.laowang

Laowang laowang2=Laowang.laowang

System.out.println (laowang1==laowang2)

}

Declare an enumerated class directly, define a property, and get it directly in the main method.

At this point, the study of "A brief introduction to the singleton pattern in the java design pattern" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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