S
S
Sword_Dancer2017-07-08 19:14:05
Design patterns
Sword_Dancer, 2017-07-08 19:14:05

What is the Visitor design pattern?

class MyClass1
{
    function accept(OperationGroup $operation) {$operation->visitMyClass1($this);}
    function method1() {}
    function method2() {}
}

abstract class OperationGroup {}
class OperationGroup1 extends OperationGroup
{
    function visitMyClass1(MyClass1 $myClass1) {$myClass1->method1(); /*.............*/ }
    function visitMyClass2(MyClass2 $myClass2) {$myClass2->method1(); /*.............*/ }
}

$myClass1 = new MyClass1();
$operationGroup1 = new OperationGroup1();

$myClass1->accept($operationGroup1);

Tell me, please, what is the essence of the Visitor design pattern? Despite all the articles I've read, it's still not clear. The methods visitMyClass1, visitMyClass2, etc. are needed, as I understand it, to encapsulate work with the source classes MyClass1, etc., but why do we need the accept method in them?
Why can't you directly call $operationGroup1->visitMyClass1($myClass1); ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Mirchenko, 2017-07-08
@KM-Brothers

Look in the book "PHP. Programming Objects, Patterns and Techniques", page 266.
I do not remember exactly, but this pattern should also be well considered in Martin Fowler's book.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question