Composite design pattern PHP example -
in client code, , @ it's simplest should read like:
<?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 ?>
however, we're attempting using composite design pattern , things become non-trivial. have been working on following:
<?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(){ /* nothing */ } } // leaf class _integer implements solution { private $_int; function __construct($_int){ $this->_int = $_int; } function f(){ /* 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(){ /* nothing */ } }
ive reached point need verbs , nouns logic behind great pattern - based around simple equation.
thanks in advance.
edit: @peehaa. admittedly, not defined. ok, i'm trying apply composite pattern arithmetic expression say:
((3 + 4 - 1) * 5 + 6 * -7) / 2
'/' / \ + 2 / \ * * / \ / \ - 5 6 -7 / \ + 1 / \ 3 4
for example, in php. first got idea from: https://sourcemaking.com/files/v2/content/patterns/composite_example1-2x.png
but struggling little , looking guidance.
Comments
Post a Comment