search
HomeBackend DevelopmentPHP TutorialPHP Design Patterns - Visitor Pattern_PHP Tutorial

PHP Design Pattern - Visitor Pattern

Visitor pattern represents an operation that acts on each element in an object structure. It allows you to define new operations on each element without changing its class.

UML class diagram:

Character:

1. Abstract visitor (State): declares an access operation interface for the specific element role in the object structure. The name and parameters of the operation interface identify the specific element role that sends the access request to the specific visitor, so that the visitor can directly access it through the specific interface of the element role.

2. Specific visitor (Success): implements the interface declared by the visitor.

3. Abstract element (Person): Define an access operation accept(), which takes a visitor as a parameter.
4. Concrete element (Man): implements the acceptance operation interface defined by the abstract element.

5. Structural object (ObjectStruct): This is a necessary role to use the visitor mode. It has the following characteristics: it can enumerate its elements; it can provide a high-level interface to allow visitors to access its elements; if necessary, it can be designed as a composite object or a collection (such as a list or unordered collection).

Core code:

<span style="color:#000000;"><!--?php
/**
 * Created by PhpStorm.
 * User:Jang
 * Date:2015/6/11
 * Tim: 9 :40
 */

/*男人这本书的内容要比封面吸引人;女人这本书的封面通常比内容更吸引人
男人成功时,背后多半有一个伟大的女人;女人成功时,背后多半有一个失败的男人
男人失败时,闷头喝酒,谁也不用劝;女人失败时,眼泪汪汪,谁也劝不了
男人恋爱时,凡事不懂也要装懂;女人恋爱时,遇事懂也要装作不懂*/
//抽象状态
abstract class State
{
    protected $state_name;

    //得到男人反应
    public abstract function GetManAction(VMan $elementM);
    //得到女人反应
    public abstract function GetWomanAction(VWoman $elementW);
}

//抽象人
abstract class Person
{
    public $type_name;

    public abstract function Accept(State $visitor);
}

//成功状态
class Success extends State
{
    public function __construct()
    {
        $this--->state_name=成功;
    }

    public  function GetManAction(VMan $elementM)
    {
        echo {$elementM->type_name}:{$this->state_name}时,背后多半有一个伟大的女人。
;
    }

    public  function GetWomanAction(VWoman $elementW)
    {
        echo {$elementW->type_name} :{$this->state_name}时,背后大多有一个不成功的男人。
;
    }
}

//失败状态
class Failure extends State
{
    public function __construct()
    {
        $this->state_name=失败;
    }

    public  function GetManAction(VMan $elementM)
    {
        echo {$elementM->type_name}:{$this->state_name}时,闷头喝酒,谁也不用劝。
;
    }

    public  function GetWomanAction(VWoman $elementW)
    {
        echo {$elementW->type_name} :{$this->state_name}时,眼泪汪汪,谁也劝不了。
;
    }
}

//恋爱状态
class Amativeness  extends State
{
    public function __construct()
    {
        $this->state_name=恋爱;
    }

    public  function GetManAction(VMan $elementM)
    {
        echo {$elementM->type_name}:{$this->state_name}时,凡事不懂也要装懂。
;
    }

    public  function GetWomanAction(VWoman $elementW)
    {
        echo {$elementW->type_name} :{$this->state_name}时,遇事懂也要装作不懂。
;
    }
}

//男人
class VMan extends Person
{
    function __construct()
    {
        $this->type_name=男人;
    }

    public  function Accept(State $visitor)
    {
        $visitor->GetManAction($this);
    }
}

//女人
class VWoman extends Person
{
    public function __construct()
    {
        $this->type_name=女人;
    }

    public  function Accept(State $visitor)
    {
        $visitor->GetWomanAction($this);
    }
}

//对象结构
class ObjectStruct
{
    private $elements=array();
    //增加
    public function Add(Person $element)
    {
        array_push($this->elements,$element);
    }
    //移除
    public function Remove(Person $element)
    {
        foreach($this->elements as $k=>$v)
        {
            if($v==$element)
            {
                unset($this->elements[$k]);
            }
        }
    }

    //查看显示
    public function Display(State $visitor)
    {
        foreach ($this->elements as $v)
        {
            $v->Accept($visitor);
        }
    }
}</span>

Test client code:

header(Content-Type:text/html;charset=utf-8);
//------------------------访问者模式--------------------
require_once ./Visitor/Visitor.php;
$os = new ObjectStruct();
$os->Add(new VMan());
$os->Add(new VWoman());

//成功时反应
$ss = new Success();
$os->Display($ss);

//失败时反应
$fs = new Failure();
$os->Display($fs);

//恋爱时反应
$ats=new Amativeness();
$os->Display($ats);

Applicable scenarios and advantages:

1) An object structure contains many class objects, they have different interfaces, and you want to perform some operations on these objects that depend on their specific classes.

2) Many different and unrelated operations need to be performed on the objects in an object structure, and you want to avoid having these operations "pollute" the classes of these objects. The Visitor pattern allows you to centralize related operations and define them in a class.

3) When the object structure is shared by many applications, use the Visitor mode to allow each application to only contain the operations it needs.

4) The class that defines the object structure rarely changes, but it is often necessary to define new operations on this structure. Changing the object structure class requires redefining the interface for all visitors, which can be costly. If your object structure classes change frequently, it may be better to define these operations in those classes.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1015540.htmlTechArticlePHP design pattern - Visitor pattern The visitor pattern represents an operation that acts on each element in an object structure . It allows you to define the effects on this without changing the class of each element...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools