Single-Case mode:
The singleton mode, also known as the duty mode, is used to create a single-function access point in the program, which is, in layman's name, unique to the instantiated object.
All singleton modes have at least the following three common elements:
1. They must have a constructor and must be marked as private
2. They have a static member variable that holds an instance of the class
3. They have a public static method that accesses this instance
Code:
<?PHPclassren{ Public $name; Private Static $DX;//Store Object//Declare a private instance variable Private function__construct ()//declares a private construction method in order to prevent external code from using new to create an object. {} Public Static functionDuixiang () {if(Empty(Self::$DX))//The Self keyword calls the static class; The static method does not need to instantiate the direct call class --method{//declares a DX () static method that detects whether an instance objectSelf::$DX=NewRen (); } returnSelf::$DX; }}//$shili =new ren ();//error//$shishi =new Ren (); //different$r= Ren::Duixiang ();$r->name = "XXX";Var_dump($r);$r 1= Ren::Duixiang ();Var_dump($r 1);?>
Factory mode:
Factory mode is a class that has some methods for creating objects for you, so you can use the factory class to create objects instead of using new directly. This way, if you want to change the type of object you create, you can simply change the factory.
Look at the code:
This is an ordinary class, there are some methods
<?PHPclassyun{ Public $a; Public $b; functionSuan () {EchoOperation; }}classJiaextendsYun//Inherit Yun{ functionSuan ()//rewrite { return $this->a+$this-b; }}classJianextendsyun{functionSuan () {return $this->a-$this-b; }}classChengextendsyun{functionSuan () {return $this->a*$this-b; }}?>
Then write a factory class
<?PHPclassgongchang{Static functionChanpin ($name) //give an argument that returns an object { Switch($name){ Case"+"://the value of an expression is compared to the value of each case in the structure. If there is a match, the code associated with the case is executed return NewJia (); Break; Case"-":return NewJian (); Break; Case"*":return NewJia (); Break; } }}$aa= Gongchang::chanpin ("+");//here to find the method matching the +//Give a "*" parameter, return to me a classVar_dump($aa);?>
PHP singleton mode and Factory mode