JAVA design patterns-Singleton and singleton

Source: Internet
Author: User

JAVA design patterns-Singleton and singleton
Reprinted please indicate the source: http://blog.csdn.net/l1028386804/article/details/45441169
I,Overview

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

II, Applicability

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

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

III, Participants

Singleton defines an Instance operation that allows the customer to access its unique Instance. An Instance is a class operation. It may be responsible for creating its own unique instance.

Iv. Category chart

V. Example

 Singleton

Package com. lyz. design. singleton;/*** create a Singleton object class * @ author liuyazhuang **/public class Singleton {/*** declare a static Singleton class variable */private static singlesing ton; /*** privatize the constructor */private Singleton () {}/ *** create a Singleton object * @ return */public static Singleton getInstance () {if (sing = null) {synchronized (Singleton. class) {if (sing = null) {sing = new Singleton () ;}} return sing ;}}

 Test

Package com. lyz. design. singleton;/*** Test class * @ author liuyazhuang **/public class Test {public static void main (String [] args) {Singleton sing = Singleton. getInstance (); Singleton sing2 = Singleton. getInstance (); System. out. println (sing); System. out. println (sing2 );}}

Result

com.lyz.design.singleton.Singleton@11f46b16com.lyz.design.singleton.Singleton@11f46b16


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.