thrashzone13/visitor

访问者设计模式的简单实现

V1.0.0 2024-07-31 14:02 UTC

This package is auto-updated.

Last update: 2024-10-01 08:21:19 UTC


README

Latest Version on Packagist Software License Total Downloads

此包提供访问者模式实现。

访问者模式

访问者是一种行为设计模式,它允许你将算法与它们操作的对象分离。

安装

通过Composer

$ composer require thrashzone13/visitor

用法

考虑一个由不同类型的形状组成的数组

$shapes = [
    new Circle(radius: 10),
    new Rectangle(width: 15, height: 20),
    new Rectangle(width: 10, height: 14),
    new Square(side: 16)
];

假设意图是计算它们的面积并将它们加起来。可以有一个访问者根据接收到的实例类型执行计算

$visitor = (new Visitor)
    ->add(fn(Circle $circle) => pi() * $circle->getRadius() * $circle->getRadius())
    ->add(fn(Square $square) => $square->getSide() * $square->getSide())
    ->add(fn(Rectangle $rectangle) => $rectangle->getWidth() * $rectangle->getHeight());

现在可以使用它了!

$totalArea = 0;
foreach ($shapes as $shape) {
    $totalArea += $visitor->visit($circle);
}

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。