[JavaSE] Singleton design mode and javase sample design mode

Source: Internet
Author: User

[JavaSE] Singleton design mode and javase sample design mode

Four-person gang designed the design pattern in 23

Singleton design mode: solves the problem that only one object exists in the memory of a class.

 

Constructor privatization

Create a class object in the class

Provides a method to obtain the object.

Class Single {private static Single single; public int num = 1; private Single () {} public static Single getInstance () {if (single = null) {single = new Single (); System. out. println ("only one object");} return single ;}} public class SingleDemo {/*** @ param args */public static void main (String [] args) {Single s1 = Single. getInstance (); s1.num = 2; Single s2 = Single. getInstance (); // only output once "the object has only one" System. out. println (s2.num); // at this time, output 2 indicates the same object }}

PHP version:

<? Phpclass Single {private static $ single; public $ num = 1; private function _ construct () {} public static function getInstance () {if (Single :: $ single = null) {Single ::$ single = new Single (); echo "only one object";} return Single ::$ single ;} /* override PHP magic Method */private function _ clone () {}} class SingleDemo {public static function main () {$ obj1 = Single: getInstance (); $ obj1-> num = 2; $ obj2 = Single: getInstance (); // only output once "the object has only one" echo $ obj2-> num; // at this time, output 2 indicates the same object} SingleDemo: main ();

 

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.