[Java design mode] java Singleton mode and java Design Mode

Source: Internet
Author: User

[Java design mode] java Singleton mode and java Design Mode

What is the singleton mode:

The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system. In computer systems, driver objects of thread pools, caches, log objects, dialogs, printers, and graphics cards are often designed as Singleton. These applications have more or less resource manager functions. Each computer can have several printers, but only one Printer Spooler can be used to prevent two print jobs from being output to the Printer at the same time. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being simultaneously called by both requests. In short, the singleton mode is selected to avoid inconsistency and avoid multiple leaders. Why do I need to use the singleton mode? For example, the configuration file reading class, when a java program is running on the service, it needs to use parameters in the configuration file at intervals, you can't keep a new object in the program every time. The best way is to create an object when starting the program, and keep using the attribute values in the object. This requires the singleton design mode. Example: 1. Lazy Singleton
public class Singleton {      private static class LazyHolder {         private static final Singleton INSTANCE = new Singleton();      }      private Singleton (){}      public static final Singleton getInstance() {         return LazyHolder.INSTANCE;      }  }  

 

Ii. Hunger-type Singleton class // hunger-type Singleton class. It has been self-instantiated during class initialization.
Public class Singleton1 {private Singleton1 () {} private static final Singleton1 single = new Singleton1 (); // static factory method public static Singleton1 getInstance () {return single ;}}

 

 

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.