复合设计模式PHP示例
在客户端代码中,最简单的情况下,它应该是这样的:复合设计模式PHP示例,php,design-patterns,Php,Design Patterns,在客户端代码中,最简单的情况下,它应该是这样的: <?php // Client code $int1 = new _Integer(2); $int2 = new _Integer(3); $operator = new Operator('+'); $op1 = new Operands($int1); $op2 = new Operands($int2); // $op1 + $operator + $op2 = Solution === 5 ?> 例如,在
<?php
// Client code
$int1 = new _Integer(2);
$int2 = new _Integer(3);
$operator = new Operator('+');
$op1 = new Operands($int1);
$op2 = new Operands($int2);
// $op1 + $operator + $op2 = Solution === 5
?>
例如,在PHP中。我最初的想法来自:
但是我有点纠结于此,并在寻找一些指导。您的代码示例没有什么意义?你的实际问题是什么也不清楚。试着修改一下你的问题,试着问一个非常清楚的问题。因为模式和复合设计模式在概念上并不容易理解,所以如果小心处理$sum=new操作(“+”,$op1,$op2),这可能是一个很好的问答步骤$减号=新运算(“-”,$sum,新操作数(新的_整数(1));
<?php
// Use case: 2 + 3 = 5
// Component
interface Solution {
function f();
}
// Composite
class Operands implements Solution {
private $ints = [];
function __construct(_Integer $_integer = null ){
$this->_integer = $_integer;
array_push($this->ints, $this->_integer);
}
function f(){ /* Do nothing */ }
}
// Leaf
class _Integer implements Solution {
private $_int;
function __construct($_int){
$this->_int = $_int;
}
function f(){ /* Do nothing */ }
function getInt(){
return $this->_int;
}
}
// Leaf
class Operator implements Solution {
private $operator;
function __construct($operator){
$valid = in_array($operator, ['+','-','/','*']);
if($valid) $this->operator = $operator;
}
function f(){ /* Do nothing */ }
}
'/'
/ \
+ 2
/ \
* *
/ \ / \
- 5 6 -7
/ \
+ 1
/ \
3 4