Design Patterns PHP - Interpreter Java

1) What have we got?

We have class "Vector" which represents mathematical concept of Vector

class Vector
{
    /**
     * @var int x
     */
    protected $x;

    /**
     * @var int y
     */
    protected $y;

    /**
     * @param int $x
     * @param int $y
     */
    public function __construct($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }

    /**
     * @param Vector $vector
     * @return Vector
     */
    public function add(Vector $vector)
    {
        return new Vector($this->x + $vector->x, $this->y + $vector->y);
    }

    /**
     * @param int $k
     * @return Vector
     */
    public function multiply($k)
    {
        return new Vector($this->x * $k, $this->y * $k);
    }
}



this class has two coordinates: "x" and "y"

We want to do basic arithmetic operations with vectors:

- adding two vectors
- multiply vector by integer

We add two methods:
-add(Vector) - returning new vector which is sum current vector and this from argument
-multiply(int) - new vector which is the product this vector and number

2) What is our goal ?

System executes basic operations on vectors but given interface is unreadable if we want create advanced expressions


$a = new Vector(2, 3);
$b = new Vector(3, 5);
$c = new Vector(1, 2);

//(a+b)*4+2*c;
$vector = $a->add($b)->multiply(4)->add($c->multiply(2));

/*
    this interface would be much more better

    Builder->build('(a+b)*4+2*c')->evaluate([
    a=> new Vector(2,3),
    b=> new Vector(3,5)
    c=> new Vector(5,8)
    ]);

*/