1.单例模式
class Danli
{
//私有化类对象存放变量
private static $_instance;
//私有化构造函数
private function __construct(){}
//私有化克隆函数
private function __clone(){}
//类实例化接口
public static function getInstance()
{
if(!(self::$_instance instanceof self))
{
self::$_instance = new self;
}
return self::$_instance;
}
//根据用户ID,获取用户名
public function getUserName($id)
{
//获取数据操作
return "返回最后的数据: {$id}";
}
}
$Danli = Danli::getInstance();
echo $Danli->getUserName(2);
2.抽象工厂模式
//定义抽象类 . 抽象方法
abstract class CreateObj{
abstract static function getValue($num1,$num2);
}
//定义加法计算类
class CalculationAdd extends CreateObj
{
public static function getValue($num1,$num2){
return $num1 + $num2;
}
}
//定义乘法计算类
class CalculationSub extends CreateObj
{
public static function getValue($num1,$num2){
return $num1 * $num2;
}
}
//定义总控制类 - 选择指定的对象类
class Calculation{
public static function getClassObj($type){
switch ($type)
{
case ‘+‘:
return new CalculationAdd();
break;
case ‘*‘:
return new CalculationSub();
break;
}
}
}
$Calculation = Calculation::getClassObj(‘+‘);
echo $Calculation->getValue(1,3);
3.简单工厂模式
//简单工厂模式: 即静态工厂模式. 简单工程模式,是通过一个静态方法创建对象
interface CreateObj
{
function getValue($num1,$num2);
}
//加法运算类
class CalculationAdd implements CreateObj
{
function getValue($num1,$num2)
{
return $num1 + $num2;
}
}
//乘法运算类
class CalculationSub implements CreateObj
{
function getValue($num1, $num2)
{
return $num1 * $num2;
}
}
//运算控制类
class SimpleFactory
{
public static function CreateAdd()
{
return new CalculationAdd();
}
public static function CreateSub()
{
return new CalculationSub();
}
}
$Add = SimpleFactory::CreateAdd();
echo $Add->getValue(1,4)."<br/>";
$Sub = SimpleFactory::CreateSub();
echo $Sub->getValue(2,3);