A single-instance pattern of Java design patterns

Source: Internet
Author: User

Scenario Issues

There is an immortal legend in the industry. Is that the program ape can't find a girlfriend. How can I do without a girlfriend?

Today we take the knowledge of Java with everyone. To "Chase" a girlfriend.
That in chasing girlfriend between, we first set a girlfriend's standard.

It's just that. This standard is not a mess, is it? Not like the Internet. "Female, Live". As an ape with an ideal program. I think my girlfriend, to have height, and then the cup is not correct low, low weight is not good too fat.

So in the Java language, this "girlfriend" has to have three attributes. Height. Weight, with a bust. So. We build this class. Called Girlfriend.

 Public classGirlfriend {PrivateString Cup;Private intHeightPrivate intWeight PublicStringGetcup() {returnCup } Public void Setcup(String Cup) { This. cup = Cup; } Public int getheight() {returnHeight } Public void setheight(intHeight) { This. height = height; } Public int Getweight() {returnWeight } Public void Setweight(intWeight) { This. Weight = weight; }}

That's now ready for a girlfriend class.

Next, is not going to produce a girlfriend.

Then we'll be in the client new one.

publicclass Client {    publicstaticvoidmain(String[] args) {        new GirlFriend();    }}

problem
Let's just try to imagine. Suppose we are in the client, and then to "find" a girlfriend, is not also able to.

publicclass Client {    publicstaticvoidmain(String[] args) {        new GirlFriend();        new GirlFriend();        System.out.println(gf==gf1);    }}

And. The code above. Finally the result is also false.
That, as a principled man, is not to limit such a situation to find it.

Singleton pattern definition for single case mode

One way to solve the above problem is to use a singleton pattern.

So what is a singleton mode? Let's first look at the definition:

Ensure that a class has only one instance and provides a global access point for it.

Implementation method

In Java. The singleton pattern implementation is divided into two kinds. One is called the lazy type, one is also called the A Hungry man type.

Let's take a look at how these two approaches are implemented.


1: Lazy Type

 Public classGirlfriend {PrivateString Cup;Private intHeightPrivate intWeight//Define a change to store the instance    Private StaticGirlfriend Instance =NULL;Private girlfriend(){    } Public StaticGirlfriendgetinstance(){//Infer if the instance is empty        if(NULL==instance) {//Assuming the current instance has not yet been created, generate one and assign it to a storage instanceInstance =NewGirlfriend (); }returnInstance }///Below are examples of demo methods     PublicStringGetcup() {returnCup } Public void Setcup(String Cup) { This. cup = Cup; } Public int getheight() {returnHeight } Public void setheight(intHeight) { This. height = height; } Public int Getweight() {returnWeight } Public void Setweight(intWeight) { This. Weight = weight; }}

2: A Hungry man type:

 Public classGirlfriend {PrivateString Cup;Private intHeightPrivate intWeight//Define a change to store the created instance    Private StaticGirlfriend Instance =NewGirlfriend ();Private girlfriend(){    } Public StaticGirlfriendgetinstance(){returnInstance }///Below are examples of demo methods     PublicStringGetcup() {returnCup } Public void Setcup(String Cup) { This. cup = Cup; } Public int getheight() {returnHeight } Public void setheight(intHeight) { This. height = height; } Public int Getweight() {returnWeight } Public void Setweight(intWeight) { This. Weight = weight; }}

3:client Call
Then this time, we call again. The only thing I got was a girlfriend.

publicclass Client {    publicstaticvoidmain(String[] args) {        GirlFriend gf = GirlFriend.getInstance();        GirlFriend gf1 =GirlFriend.getInstance();        System.out.println(gf==gf1);    }}

Because we're in the girlfriend class, the construction method is privatized, so. When the client side is called. Got the only one girlfriend object.

(Here we are temporarily not considering reflections.) )
4: About naming
In fact, the so-called a hungry man and the lazy is also a comparative image of the argument it.


The so-called a hungry man. That means you're hungry and thirsty, so you've created your "girlfriend" When you load the class. The lazy one. That's lazy. You can create it when you need a girlfriend.

Delayed loading and cache delay loading

The lazy singleton model embodies the idea of delayed loading. So what is delayed loading.
In a simple way, delay loading is the start of not loading data or resources, waiting to be used, only to load, that is, Lazy load.

This is also a common idea in practical development, saving resources as much as possible.

Cache

Lazy also embodies the idea of caching, caching in development is also a common feature.
In simple terms, it is when some resources need to be reused, and these resources are stored outside the system. For example, database, hard disk, etc. That assumes that each operation is read again. Obviously a very wasteful resource. So, lazy loading, in the beginning, defined a variable. To store the instance to be generated. That is

privatestatic GirlFriend  instance =null;

After that, the instance is generated and assigned to the variable.

Thread Safety

In terms of thread safety. Non-synchronized lazy-type is thread insecure.

Other words. Assuming multiple threads call the GetInstance method at the same time, the concurrency problem is directed. How to solve it.

In fact, just add synchronized to it. That is

  publicstaticsynchronizedgetInstance(){}

But that will reduce the speed of access. And you have to infer it every time. That's how it should be implemented, and it's going to use double locking.


The so-called double lock. Refers to. Not every time getinstance to synchronize.

Instead of stepping into the method first, check to see if the instance exists.

assumption does not exist. Again into the sync block, this is the first check. After entering the synchronization block. Check again if the instance exists, assuming it does not exist. Creates an instance in the synchronization scenario. This is the second heavy check. In this way, you can reduce the time wasted on multiple inferences in a synchronous situation.
Implementation code such as the following:

  privatevolatilestatic GirlFriend  instance =null;    publicstatic  getInstance(){        if(null==instance){            synchronized (GirlFriend.class){                if(instance==null){                    new GirlFriend();                }            }        }        return instance;    }

Note: Dual loading requires a version number above Java5.

Enumeration

In fact, another more efficient single-instance implementation. This is the enumeration of single elements. As for the introduction of enumerations, I do not introduce more here.

Let's look at how to use enumerations to implement a singleton.

 Public enumGirlfriend {instance;PrivateString Cup;Private intHeightPrivate intWeight///Below are examples of demo methods     PublicStringGetcup() {returnCup } Public void Setcup(String Cup) { This. cup = Cup; } Public int getheight() {returnHeight } Public void setheight(intHeight) { This. height = height; } Public int Getweight() {returnWeight } Public void Setweight(intWeight) { This. Weight = weight; }}

Using enumerations to implement a single meeting makes the code more concise. And. The absolute prevention of multiple instantiation from the JVM.

A single-instance pattern of Java design patterns

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.