<?php
interface MathStrategy
{
public function calculate(int $a, int $b): int;
}
class Addition implements MathStrategy
{
public function calculate(int $a, int $b): int
{
return $a + $b;
}
}
class Multiplication implements MathStrategy
{
public function calculate(int $a, int $b): int
{
return $a * $b;
}
}
class MathContext
{
private $strategy;
public function __construct(MathStrategy $strategy)
{
$this->strategy=$strategy;
}
public function setStrategy(MathStrategy $strategy): void
{
$this->strategy=$strategy;
}
public function calculate(int $a, int $b): int
{
return $this->strategy->calculate($a, $b);
}
}
$context=new MathContext(new Addition());
echo $context->calculate(2, 3) . “\n”; // output: 5
$context->setStrategy(new Multiplication());
echo $context->calculate(2, 3) . “\n”; // output: 6
interface MathStrategy
{
public function calculate(int $a, int $b): int;
}
class Addition implements MathStrategy
{
public function calculate(int $a, int $b): int
{
return $a + $b;
}
}
class Multiplication implements MathStrategy
{
public function calculate(int $a, int $b): int
{
return $a * $b;
}
}
class MathContext
{
private $strategy;
public function __construct(MathStrategy $strategy)
{
$this->strategy=$strategy;
}
public function setStrategy(MathStrategy $strategy): void
{
$this->strategy=$strategy;
}
public function calculate(int $a, int $b): int
{
return $this->strategy->calculate($a, $b);
}
}
$context=new MathContext(new Addition());
echo $context->calculate(2, 3) . “\n”; // output: 5
$context->setStrategy(new Multiplication());
echo $context->calculate(2, 3) . “\n”; // output: 6
© 版权声明
文章版权归作者所有,未经允许请勿转载。