On the Java design pattern--Singleton mode (Singleton)

Source: Internet
Author: User

Reprint Please specify Source: http://blog.csdn.net/l1028386804/article/details/45441169
One Overview

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

Two Applicability

1. When a class can have only one instance and the customer can access it from a well-known access point.

2. When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.

Three participants

Singleton defines a instance operation that allows a client to access its only instance. Instance is a class operation. may be responsible for creating its own unique instance.

Four, class diagram

V. Examples

Singleton

Package com.lyz.design.singleton;/** * Class for creating singleton objects * @author Liuyazhuang * */public class Singleton {    /**     * declares a static sin Gleton class Variable     */    private static Singleton sing;    /**     * Construction Method Privatization * *    Private Singleton () {}    /**     * Create Singleton     * @return *     /public    static Singleton getinstance () {        if (sing = = null) {            synchronized (singleton.class) {if (sing = = null) {sing = new single ton ();        }}} return sing;}    }

Test

Package com.lyz.design.singleton;/** * Testing class * @author Liuyazhuang * */public class Test {public        static void main (Strin G[] args) {        Singleton sing = Singleton.getinstance ();        Singleton sing2 = Singleton.getinstance ();                System.out.println (sing);        System.out.println (sing2);    }}

Result

[Email protected] [Email protected]


On the Java design pattern--Singleton mode (Singleton)

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.