php简单工厂模式
2024-08-26 12:06:04
工厂类中有一个创建对象的方法,根据传入参数的不同来生成不同的对象
class Operation extends Model
{ private $numberA;
private $numberB; public function getResult(){ $result = 0; return $result; } public function getNumberA(){ return $this->numberA;
}
public function setNumberA($numberA){ $this->numberA = $numberA; } public function getNumberB(){ return $this->numberB;
}
public function setNumberB($numberB){ $this->numberB = $numberB; } }
class OperationAdd extends Operation
{ public function getResult()
{
$result = 0 ; $result = $this->numberA + $this->numberB; return $result; } }
class OperationSub extends Operation
{ public function getResult()
{
$result = 0; $result = $this->numberA - $this->numberB; return $result;
} }
class OperationMul extends Operation
{
public function getResult(){ $result = 0; $result = $this->numberA * $this->numberB; return $result; } }
class OperationDiv extends Operation
{
public function getResult(){ $result = 0;
if ($this->numberA == 0){ throw new HttpException("除数不能为0");
} $result = $this->numberA / $this->numberB; return $result;
}
}
class Factory extends Model
{ private $type; public function __construct($type,array $config = [])
{
$this->type = $type;
parent::__construct($config);
} public function createOperate(){
switch ($this->type){
case "+": return new OperationAdd(); break; case "-": return new OperationSub(); break; case "*": return new OperationMul();
break; case "/": return new OperationDiv();
break; }
} }
$factory = new Factory("+"); $operation = $factory->createOperate(); $operation->numberA = 2; $operation->numberB = 1; $result = $operation->getResult(); echo $result;
最新文章
- c# 读取mck码
- 【原创】开源Math.NET基础数学类库使用(03)C#解析Matlab的mat格式
- 通过setTimeout来取消因大量计算造成的网页卡顿
- java中的访问修饰符
- 打出10的n次方,上标,下标等处理方法(mac)
- JavaScript本地对象 内置对象 宿主对象
- 进程间通信(IPC)介绍
- oc-22-sel
- Python list去重及找出,统计重复项
- .bash_profile与.bashrc和.profile的区分概念
- Java模式(适配器型号)
- python 自动化之路 day 14
- class AClass<;E extends Comparable>;与class AClass<;E extends Comaprable<;E>;>;有什么区别?
- 【Python学习】yield send我就说这么多
- python爬虫随笔(2)—启动爬虫与xpath
- VNC安装配置
- redis之数据类型以及使用
- 页面练习my blog day51
- 【java】详解集合
- bzoj1799(洛谷4127)同类分布(月之谜)
热门文章
- PostgreSQL学习资料
- B10:迭代器模式 Iterator
- B9:备忘录模式 Memento
- mysql 5.6 修改root原始密码不为空方法
- jsoup爬虫简书首页数据做个小Demo
- 导入解析excel小结
- win10 rabbitMQ的安装与测试
- Failed to load http://localhost:8080/team.php: Request header field x-jwt-header is not allowed by Access-Control-Allow-Headers in preflight response.
- hMailServer 附件大小限制
- AES中几种加密模式的区别:ECB、CBC、CFB、OFB、CTR