jeudi 14 juin 2018

Visitor Pattern, why is it useful?

I used the Visitor example given here Where we have this:

.------------------------.
|        Flower          |
+------------------------+ 
| +accept(visitor)       |
| +pollinate(pollinator) |
| +eat(eater)            |
'------------------------'

We also have a Bug and a Bee that can pollinate a Flower, and a Predator that can eat a flower.

Using the vistor pattern I can write this:

bee = Bee()
fly = Fly()
worm = Worm()

# Using the visitor pattern:
for flower in flowerGen(10):    
    for object in [bee, fly, worm]:
        flower.accept(object)

But the code is as readable and funcitonal without the visitor:

# Without visitor pattern 
for flower in flowerGen(10):
    for object in [bee, fly, worm]:
        object.visit(flower)

The question is, what advantages provide the Visitor Pattern in this example?

Aucun commentaire:

Enregistrer un commentaire