PHP程序员日记

PHP设计模式应用实例(多态模式,工厂模式,命令模式)

2019-08-22  本文已影响0人  PHP程序媛

1、多态模式

<?

class pub {

     protected function working() {

         echo '这是一个可以重写的方法'; 

     }

}

class student extends pub {

     public function working() {

          echo '学生在学习';

     }

}

class teacher extends pub {

     public function working() {

          echo '老师在讲课';

     }

}

public function doing($obj) {

     if ($obj instanceof pub) {

          $obj->working();

     } else {

          echo '没有这个对象!';

     }

}

doing(new student());

doing(new teacher());

?>

2、工厂模式:根据传入的类型名实例化对象,只负责生成对象,而不负责对象的具体内容

//定义一个适配器接口

interface Db_Adapter{

public function connect();

public function query();

}

//定义MySQL数据库操作类

class Db_Adapter_Mysql implements Db_Adapter{

public function connect(){

echo "mysql数据库连接操作";

}

public function query(){

echo "mysql数据库查询操作";

}

}

//定义SQLite数据库操作类

class Db_Adapter_Sqlite implements Db_Adapter{

public function connect(){

echo "sqlite数据库连接操作";

}

public function query(){

echo "sqlite数据库查询操作";

}

}

//定义工厂类

class sqlFactory{

public static function factory($type) {

$classname = 'Db_Adapter_'.$type;

return new $classname;

}

}

//调用

$db = sqlFactory::factory('Mysql');

$db = sqlFactory::factory('Sqlite');

3、命令模式

//定义厨师类,命令接受者与执行者

class cook{

public function meal() {

echo "西红柿炒鸡蛋<br>";

}

public function drink() {

echo "紫菜蛋花汤<br>";

}

public function ok() {

echo "完成<br>";

}

}

//命令接口

interface command{

public function execute();

}

//模拟服务员与厨师的过程

class mealCommand implements command{

private $cook;

public function __construct($cook){

$this->cook = $cook;

}

public function execute(){

$this->cook->meal();

}

}

class drinkCommand implements command{

private $cook;

public function __construct($cook){

$this->cook = $cook;

}

public function execute(){

$this->cook->drink();

}

}

//模拟顾客与服务员的过程

class cookControl{

private $mealCommand;

private $drinkCommand;

public function addCommond($mealCommand,$drinkCommand) {

$this->mealCommand = $mealCommand;

$this->drinkCommand = $drinkCommand;

}

public function callMeal(){

$this->mealCommand->execute();

}

public function callDrink(){

$this->drinkCommand->execute();

}

}

//实现命令模式

$cookControl = new cookControl();

$cook = new cook();

$mealCommand = new mealCommand($cook);

$drinkCommand = new drinkCommand($cook);

$cookControl->addCommond($mealCommand,$drinkCommand);

$cookControl->callMeal();

$cookControl->callDrink();

上一篇下一篇

猜你喜欢

热点阅读