版权声明:欢迎转载,请标明出处~ https://blog.csdn.net/chenshuai1993/article/details/54408625
策略模式(strategy):
策略模式定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户
/**
* FILE_NAME:factory.php
* AUTHOR: ChenShuai
* Date: 2017/1/13
* DESC:
*/
interface animal
{
/**
* @return mixed
* @author chenss
* @email [email protected]
* @desc 吃
*/
public function eat();
/**
* @return mixed
* @author chenss
* @email [email protected]
* @desc 跑
*/
public function run();
}
/**
* Class factory
* 工厂类
*/
class factory
{
private $type;
public $obj;
function __construct($type)
{
//工厂模式 && 策略模式结合(用户看到的类 更少了,耦合性更加降低)
$this->obj = new $this->type();
return new $this->type();
}
public function behavior()
{
$this->obj->eat();
}
}
/**
* Class person
* 人
*/
class person implements animal
{
public function eat()
{
echo '我是人类的吃';
}
public function run()
{
echo '我是人类的跑';
}
}
/**
* Class tiger
* tiger
*/
class tiger implements animal
{
public function eat()
{
echo '我是老虎的吃';
}
public function run()
{
echo '我是老虎的跑';
}
}
//用户传递不同的参数,调用同样的方法,就可以得到不同的结果
//简单工厂模式
$type = 'person';
//简单工厂模式
/*$factory = new factory($type);
$obj = $factory->createObj();
$obj->eat();*/
//策略模式 && 简单工厂模式
$factory = new factory($type);
$factory->behavior();