Skip to content

Instantly share code, notes, and snippets.

@lloy0076
Created July 27, 2023 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lloy0076/fdd373e6cbd8fe273c9943a8b9656c9c to your computer and use it in GitHub Desktop.
Save lloy0076/fdd373e6cbd8fe273c9943a8b9656c9c to your computer and use it in GitHub Desktop.
// Singleton Class
class SumSingleton
{
private static $instance;
private $result;
private function __construct() {}
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function sumArray($arr)
{
$this->result = array_sum($arr);
}
public function getResult()
{
return $this->result;
}
}
// Strategy Interface
interface SumStrategy
{
public function sumArray($arr);
}
// Concrete Strategy - Using array_sum
class ArraySumStrategy implements SumStrategy
{
public function sumArray($arr)
{
return array_sum($arr);
}
}
// Concrete Strategy - Using loop
class LoopSumStrategy implements SumStrategy
{
public function sumArray($arr)
{
$sum = 0;
foreach ($arr as $num) {
$sum += $num;
}
return $sum;
}
}
// Context (Context acts as a strategy manager)
class SumContext
{
private $strategy;
public function setStrategy(SumStrategy $strategy)
{
$this->strategy = $strategy;
}
public function sumArray($arr)
{
return $this->strategy->sumArray($arr);
}
}
// Decorator to add sum functionality
class SumDecorator
{
protected $arraySum;
public function __construct(ArraySum $arraySum)
{
$this->arraySum = $arraySum;
}
public function sum()
{
return $this->arraySum->sum();
}
}
// Usage
$a = [1, 2, 3];
// Singleton
$sumSingleton = SumSingleton::getInstance();
$sumSingleton->sumArray($a);
$sumResultSingleton = $sumSingleton->getResult();
// Strategy - array_sum
$sumContext = new SumContext();
$sumContext->setStrategy(new ArraySumStrategy());
$sumResultStrategyArraySum = $sumContext->sumArray($a);
// Strategy - loop
$sumContext->setStrategy(new LoopSumStrategy());
$sumResultStrategyLoop = $sumContext->sumArray($a);
// Decorator
$arraySum = new ArraySum($a);
$sumDecorator = new SumDecorator($arraySum);
$sumResultDecorator = $sumDecorator->sum();
echo "Sum using Singleton: " . $sumResultSingleton . "\n";
echo "Sum using Strategy (array_sum): " . $sumResultStrategyArraySum . "\n";
echo "Sum using Strategy (loop): " . $sumResultStrategyLoop . "\n";
echo "Sum using Decorator: " . $sumResultDecorator . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment