Design mode: Singleton mode, lazy and a hungry man Factory mode

Source: Internet
Author: User

In some cases, some objects require only one, in other words, each class requires only one instance. For example, one computer is connected to multiple printers, but there is only one print program on this computer, and a singleton mode is required to prevent the printer from being entered into the printer from left to right. 、

The role of the singleton pattern is to ensure that, at any one time, instances of the Singleton class only exist for the entire application life cycle. There are three main characteristics of the singleton mode:

1. A singleton class can have only one instance

2. The Singleton class must create its own unique instance.

3. The Singleton class must provide this instance for other objects.

So how do you implement a singleton class that meets the above criteria? The answer is:

1. Private construction methods.

2. Create a static object internally.

3. Provide a static method to return the static object.

There are two main ways to implement the single-case design pattern: a hungry man and lazy.

1. A hungry man type singleton: At the beginning of the definition, you instantiate yourself.

public class Single0 {
Private Single0 () {
Private construction methods
}
private static Single0 s=new Single0 ();//Create static method internally, instantiate
public static Single0 Getsingle () {
Return s;//provides a static method that returns the object
}
}

2. Lazy-type singleton: Instantiate yourself on the first call.

Class single1{
Private Single1 () {
Private construction methods
}
public static Single1 S=null;
public static Single1 Getsingle () {
S=new Single1 ();//instantiation
return s;
}
}

What is the difference between the A hungry man and the lazy?

1. Thread Safety:

A hungry man is inherently thread-safe and can be used directly for multithreading without problems.

The lazy type itself is non-thread-safe and requires man-made thread safety.

2. Resource Loading and performance:

A hungry man a static object is instantiated at the same time as the class is created, and will occupy a certain amount of memory, resulting in memory leaks, regardless of whether or not the singleton will be used later, but correspondingly, the speed will be faster on the first call.

And the lazy type as the name implies, will delay loading, in the first use of the singleton when the object will be instantiated, the first call to do the initialization, if you want to do more work, performance will be somewhat delayed, and then the same as the A Hungry man type.

To ensure lazy thread safety, there are typically three ways to do this:

1. Global access point plus synchronization.

Since synchronized is a lock method, when two threads are going to enter Getsingle (), only one can enter and create an instance, and then another one enters, judging S is not null and then directly getting s. There is no mistake in this practice. However, because threads are required to get objects through Getsingle (), the Getsingle () call frequency is high, so threads are locked at a high frequency, so this approach is inefficient. In short, regardless of whether the object has been created, the remaining threads can only wait for the lock on this method.

Class single1{
Private Single1 () {
Private construction methods
}
public static Single1 S=null;
public static synchronized Single1 Getsingle () {
S=new Single1 ();//instantiation
return s;
}
}


2. Double check lock.

Since all of these are waiting for the lock of the synchronization method, it is easy to think of putting synchronized in the method, which avoids blocking the method.

Class single2{
Private Single2 () {
Private construction methods
}
public static Single2 S=null;
public static Single2 Getsingle () {
if (s==null) {
Synchronized (Single2.class) {
S=new Single2 ();//instantiation
}
}
return s;
}
}

This kind of writing seems to have no problem, in fact, there is a big hidden trouble, is: If two threads execute Getsingle (), judge instance is not NULL, enter if judgment statement. This time a thread gets a lock, then enters new object and happily executes it. This time another thread gets the lock, but let it not judge whether S is null, so it will also perform the new operation again. So there are two new operations performed here. Of course, the last S is the only object that points to the next new one.
So this time requires a double lock, that is, in the synchronized to add a null judgment, as follows:

Class single3{
Private Single3 () {
Private construction methods
}
public static Single3 S=null;
public static Single3 Getsingle () {
if (s==null) {
Synchronized (Single3.class) {
if (s==null) {
S=new Single3 ();//instantiation
}
}
}
return s;
}
}

3. Static internal classes: both thread safety and the performance impact of synchronization are avoided.
---------------------
model1220
Source: CSDN
Original: 78218146?utm_source=copy
Copyright NOTICE: This article is for bloggers original article, reprint please attach blog link!

Handwriting Factory mode:

Interface ifactory{
Public iproduct createproduct ();}
Class Factory implements ifactory{
Public IProduct createproduct () {return new Product ();}}
public class client{
Public Static void Main (String [] args) {ifactory factory=new factory ();
IProduct product=factory.createproduct ();
Product. Productmethod ();}}
---------------------
Hopeplus
Source: CSDN
Original: 78647466?utm_source=copy
Copyright NOTICE: This article is for bloggers original article, reprint please attach blog link!

Design mode: Singleton mode, lazy and a hungry man (turn) Factory mode

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.