One, single case mode
A class can only instantiate one object
Class Ren
{
private static $DX; used to store generated objects, static methods call static members
Public $name;
Private Constructors
Private Function __construct ()
{
}
methods for generating objects
public static function Duixiang ()
{
if (Empty (self:: $DX))// determines if NULL, if NULL, new object
{
Self:: $DX = new Ren ();
}
Return self:: $DX;
}
}
$r = Ren::D Uixiang ();
$r->name = "Zhang San";
$r 1 = Ren::D Uixiang ();
Var_dump ($r 1);
Second, the factory model
The first way: not High Security
Class Suan
{
public $a;
Public $b;
function Jia ()
{
return $this->a+ $this->b;
}
Function Jian ()
{
return $this->a-$this->b;
}
}
$s =new Suan ();
$s->a=10;
$s->b=5;
echo $s->jia ();
The second way: scalability is strong
Class Yunsuan
{
public $a;
Public $b;
function Suan ()
{
}
}
Class Jia extends Yunsuan
{
function Suan ()
{
return $this->a+ $this->b;
}
}
Class Jian extends Yunsuan
{
function Suan ()
{
return $this->a-$this->b;
}
}
$s = new Jia ();
$s->a=10;
$s->b=5;
echo $s->suan ();
The Third Way: Factory mode
Objective: The disadvantage of solving the second approach: when there are many subclasses, the method name may be heavy, and thus different objects can be determined by different operators
Class Yunsuan
{
public $a;
Public $b;
function Suan ()
{
}
}
Class Jia extends Yunsuan
{
function Suan ()
{
return $this->a+ $this->b;
}
}
Class Jian extends Yunsuan
{
function Suan ()
{
return $this->a-$this->b;
}
}//To this end is the same as the second way; The purpose is to solve when there are many subclasses, the method name may be heavy, so that different classes can be determined by different operators
Class Gongchang
{
static function Shengchan ($f)
{
Switch ($f)
{
Case "+":
return new Jia ();
Break
Case "-":
return new Jian ();
Break
}
}
}
$r = Gongchang::shengchan ("-");
$r->a=10;
$r->b=5;
echo $r->suan ();
PHP singleton mode and Factory mode