Selftype: an idea from Scala for D2.0
Reiner Pope
some at address.com
Sat May 26 18:23:55 PDT 2007
eao197 wrote:
> Disclaimer. Yes, I know that Sensor could mixin Subject, not inherit it.
> But I think there is probability that in some situation inheritance must
> be used by some very important reasons.
I think mixins actually are the best way to do this. Here's how they
would look with your example (note that there is very little
modification of the code):
> template Subject(O, S)
> {
> private O[] observers_ = [];
>
> public void subscribe(O observer)
> {
> observers_ ~= observer;
> }
>
> public void publish()
> {
> foreach ( o; observers_ )
> o.notify( this );
> }
> }
>
> interface Observer(S)
> {
> void notify(S subj);
> }
>
> class Sensor
> {
> mixin Subject!(Display, Sensor);
>
> private char[] label_;
> private double value_;
>
> this( char[] label, double value )
> {
> label_ = label.dup;
> value_ = value;
> }
>
> char[] label() { return label_; }
> double value() { return value_; }
> void value( double v ) { value_ = v; publish; }
> }
>
> class Display : Observer!(Sensor)
> {
> void notify( Sensor subj )
> {
> Stdout( subj.label )( " has value " )( subj.value ).newline;
> }
> }
Using the syntax Subject is S automatically requires that any
implementors of Subject!(Display, Sensor) inherit from Sensor. So why
not simply make Sensor the inheritance root, as the mixin does? I don't
see that any information is lost this way.
-- Reiner
More information about the Digitalmars-d
mailing list