<?php /** * @Description: 策略模式 * @Author: luoxiaojin * @Date: 2020-06-29 16:57:41 * @LastEditors: luoxiaojin * @LastEditTime: 2020-06-29 21:24:18 * @FilePath: \design_patterns\l7.php */ // 通用计算机 interface Complute{ public function calc($op1,$op2); } class CompluteAdd implements Complute{ public function calc($op1,$op2){ return $op1 + $op2; } } class CompluteDiv implements Complute{ public function calc($op1,$op2){ return $op1 / $op2; } } class CompluteMult implements Complute{ public function calc($op1,$op2){ return $op1 * $op2; } } class CompluteDrop implements Complute{ public function calc($op1,$op2){ return $op1 - $op2; } } // 封装一个虚拟计算器,聚合多个真实计算器,和工厂模式的区别是:不触碰产生的对象,而是作为一个部件聚合到虚拟类中 class VComplute{ protected $js = null; public function __construct($type){ $type = 'Complute'.$type; $this->js = new $type(); } public function calc($op1,$op2){ return $this->js->calc($op1,$op2); } } $vc = new VComplute('Mult'); echo $vc->calc(1,5);
点击 "运行实例" 按钮查看在线实例
——学习参考与 bilibili燕十八 面向对象与设计模式