单例模式: 作用范围内一个类只有一个它的实例
/**单例模式
* 类里设计方法, 返回类的唯一实例
*/
class a{
public $name ;
private static $instance ;
public function __construct($name){
$this->name = $name ;
echo "实例化";
}
public static function getInstances($name){
if(!self::$instance){
self::$instance = new a($name);
return self::$instance ;
}
else return self::$instance ;
}
}
$b = a::getInstances(1);
echo $b->name ;
$b->getInstances(2);
echo $b->name ;
抽象工厂模式: 包括抽象工厂, 具体工厂 ; 抽象产品, 具体产品 . 将行为和事物本身分离 ; 将实例化操作再封装
/*抽象工厂模式*/
interface factory{
function getOperator();
}
class addFactory implements factory{
function getOperator(){
return new addOperator();
}
}
class subFactory implements factory{
function getOperator(){
return new subOperator();
}
}
class operator{
protected $num1 , $num2 ;
function setNum($num1 , $num2){
$this->num1 = $num1;
$this->num2 = $num2;
}
function getResult(){
echo null;
}
}
class addOperator extends operator
{
function getResult()
{
echo ($this->num1 + $this->num2);
}
}
class subOperator extends operator
{
function getResult()
{
echo ($this->num1 - $this->num2);
}
}
class client
{
static function main()
{
$factory = new addFactory();
$operator = $factory->getOperator();
$operator->setNum(1,2);
$operator->getResult();
$factory = new subFactory();
$operator = $factory->getOperator();
$operator->setNum(1,2);
$operator->getResult();
}
}
client::main();
image.png
demo参考 : https://blog.csdn.net/clevercode/article/details/53044679
网友评论