A single-instance design pattern for Java design patterns

Source: Internet
Author: User

Java Singleton design pattern, there are many ways to implement, the following describes some of the more famous implementation methods

    1. A Hungry man type

      This design pattern is simple, and there is no multi-threading security problem, which is generally used in practical development.

Class Hungerydemo{private Hungerydemo () {}private static final Hungerydemo instance = new Hungerydemo ();p ublic static Hung Erydemo getinstance () {return instance;}}

2. Lazy Type

This mode is delayed loading and is highly efficient.

This design pattern is more complex, there are multithreading security problems. You can use synchronous functions or synchronize blocks of code to avoid each

Determine the lock, use synchronous code block and double judge the way to solve the thread safety problem. Note that the lock should be a byte-code file for the class


Class Lazydemo{private Lazydemo () {}private static Lazydemo instance = Null;public static Lazydemo getinstance () {if ( Instance==null) {synchronized (Lazydemo.class) {if (instance==null) {instance = new Lazydemo ();}}} return instance;}}


This article is from the "line of the World" blog, please be sure to keep this source http://4259297.blog.51cto.com/4249297/1657214

A single-instance design pattern for 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.