The Singleton mode can be used in the following two forms:

Source: Internet
Author: User

The Singleton mode can be used in the following two forms:

Singleton Mode features: Solves the uniqueness of a class in the memory, and the class has only one object.

Steps for writing the singleton mode:

1. Private modifier Constructor

2. In the member position of this class, the new class Object

3. Provide a static method to return the objects of this class.

A: A tough guy

Package demo01;/*** single-instance Design Pattern tough style * @ author Administrator **/public class SingleDesignModel1 {// private constructor private SingleDesignModel1 () {}// in the position of your member variables, new private static final SingleDesignModel1 singleDesignModel1 = new SingleDesignModel1 (); // provides a static method, returns a public static SingleDesignModel1 getInstance () {return singleDesignModel1 ;}}

B: lazy

Package demo01;/*** example mode lazy * @ author Administrator **/public class SingleDesignModel2 {private static SingleDesignModel2 singleDesignModel2 = null; private SingleDesignModel2 () {} public static SingleDesignModel2 getInstance () {if (singleDesignModel2 = null) {singleDesignModel2 = new SingleDesignModel2 ();} return singleDesignModel2 ;}}

Operating principle of Singleton 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.