[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 ();