Understanding of "programming to interface"

From: bobsled (sleding_at_sands.com)
Date: 04/24/04


Date: Sat, 24 Apr 2004 18:19:02 GMT

Here's a good exmaple I found at this forum:

                        attacks 1
[Predator] --------------------- [Prey]
                                + takeLunch
                                     A
                                     |
                     +---------------+------------------+
                     | | |
                 [Gazelle] [Bird] [Brontosaurus]
                  + run + takeFlight + Stomp

And I code it as:

class Prey
{
public:
 virtual void takeLunch() = 0;
};

class Predator
{
 Prey* p;
public:
 Predator(Prey* n) : p(n) {}
 void haveFood() { p->takeLunch(); }
};

class Gazelle : public Prey
{
 void run() { }
public:
 void takeLunch() { run(); }
};

class Bird : public Prey
{
 void takeFlight() { }
public:
 void takeLunch() { takeFlight(); }
};

class Brontosaurus : public Prey
{
 void stomp() { }
public:
 void takeLunch() { stomp(); }
};

int main()
{
    Bird b;
    Predator pred(&b);
    pred.haveFood();
    return 0;
}

Do you think any modification needed for the code? Thanks you very much!