std.patterns: it was about time

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sun Feb 1 09:39:00 PST 2009


Ary Borenszweig wrote:
> Andrei Alexandrescu escribió:
>> In wake of the increasing power of templates in D2, I am starting the 
>> std.patterns module, which is to contain boilerplate for a number of 
>> common design patterns (as in the GoF book). For now I'm adding a 
>> Visitor implementation, which was lying in my codebase for a while.
>>
>> http://ssli.ee.washington.edu/~aalexand/d/web/phobos/std_patterns.html
>> http://ssli.ee.washington.edu/~aalexand/d/web/phobos/std_patterns.d
>>
>> Comments and suggestions are as always welcome.
> 
> It's nice to implement patterns with mixins, like Singleton in my video.
[...]

Thanks for sharing your insights. So far Visitor is concerned with I 
disagree with the "automatically" here. Visitor has one purpose in life: 
you call accept() with the appropriate visitor, it calls visit() back 
with the appropriate type. That's a lot of saved boilerplate already. 
However, the notion of visitable children is not captured yet, and 
probably it should.

> So maybe the visitor pattern should be implemented like this:
> 
> ---
> class BinaryExp {
> 
>   Exp leftOperand;
>   Exp rightOperand;
> 
>   mixin MakeVisitable!(leftOperand, rightOperand);
> 
> }
> ---

Not bad.

> Also, since you normally write visitors for the same conceptual 
> hierarchy, you'd like to do something like this:
> 
> ---
> auto expHierarchy = VisitorHierarchy!(BinaryExp, PrefixExp, Number, 
> Parenthesis);
> 
> class Calculator : Visitor!(expHierarchy) {
> 
>   // ...
> 
> }
> ---

That's already in:

alias TypeTuple!(BinaryExp, PrefixExp, Number, Parenthesis
     ExpHierarchy;
class Calculator : Visitor!(ExpHierarchy)
{
     ...
}

> And the Visitor should be an abstract class where every visit method 
> returns true by default. In that way you can extend it and overrite just 
> the methods you need in your visitor.

Sometimes you need strict visitation, some other times you need 
non-strict visitation. We should capture both.

> Well... just thoughts. There are a lots of ways to implement this 
> pattern, but I find this one the most useful.

A good generic implementation would save the repetitive part without 
disallowing you from being creative.


Andrei



More information about the Digitalmars-d mailing list