您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
设计模式-策略模式
发布时间:2017-11-30 09:18:32编辑:雪饮阅读()
<?php
header('content-type:text/html;charset=utf-8');
//计算接口
interface Math{
public function calc($op1,$op2);
}
//实现计算接口中的加法计算
class MathAdd implements Math{
public function calc($op1,$op2){
return $op1+$op2;
}
}
//实现计算接口中的减法计算
class MathSub implements Math{
public function calc($op1,$op2){
return $op1-$op2;
}
}
//实现计算接口中的乘法计算
class MathMul implements Math{
public function calc($op1,$op2){
return $op1*$op2;
}
}
//实现计算接口中的除法计算
class Mathdiv implements Math{
public function calc($op1,$op2){
return $op1/$op2;
}
}
//封装一个虚拟计算机
class CMath{
protected $calc=null;
public function __construct($type){
$calc='Math'.$type;
$this->calc=new $calc();
}
public function calc($op1,$op2){
return $this->calc->calc($op1,$op2);
}
}
$type=$_POST['op'];
$cmath=new CMath($type);
echo $cmath->calc($_POST['op1'],$_POST['op2']);
/*
该模式与工厂模式很相似。
工厂相当于黑盒子,策略相当于白盒子。
工厂模式:有一天你决定去吃披萨,一看菜单,哦,种类很多呀,你就点了个培根披萨,过了二十分钟,你的披萨就来了就可以吃到了。但这个披萨是怎么做的,到底面粉放了多少,培根放了多少,佐料放了多少,有多少到工序,你是不需要管的,你需要的是一个美味培根披萨。
策略模式:同样还是在披萨店,你要一个培根披萨,老板说想吃自己去做吧。原料有培根、面粉、佐料。工序有1、2、3工序,你自己去做吧。然后你就需要自己去做,到底放多少培根,放多少面粉,放多少佐料,这都你自己来决定,工序1、2、3,你是怎么实现的,都你自己决定。最后你得到了披萨。
*/
?>
关键字词:设计模式,策略模式
上一篇:设计模式-PHP实现观察者模式
下一篇:设计模式-单例模式