Re: question about interfaces
On Jan 28, 4:15 pm, Farcus Pottysquirt <where_is_my_...@movies.net>
wrote:
Sorry for the lengthiness of this post, but in order to illustrate my
question, I needed to include all the relevant classes.
I am working through a book on design patterns (Head First Design
Patterns) and the first set of code sets up a duck system. The
original MallardDuck class:
public class MallardDuck extends Duck {
/** Creates a new instance of MallardDuck */
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
public void display()
{
System.out.println("I'm a real mallard duck");
}
}I was just curious so I added a second flyBehavior:
public class MallardDuck extends Duck {
/** Creates a new instance of MallardDuck */
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
flyBehavior = new FlyNoWay();
snipped...
Why would it not show the results from both flyBehavior references like such
init:
deps-jar:
compile-single:
run-single:
Quack
I'm flying
I can't fly
BUILD SUCCESSFUL (total time: 1 second)
Because there is only one 'flyBehaviour' reference and it was over
written to point to an instance of the 'FlyNoWings' class.
To get both behaviours, you would could over ride the
Duck.performFly() method to call fly() on two 'flyBehaviour classes.
e.g.
public class MallardDuck extends Duck {
private FlyBehaviour flyBehaviour1;
private FlyBehaviour flyBehaviour2;
/** Creates a new instance of MallardDuck */
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior1 = new FlyWithWings();
flyBehavior2 = new FlyNoWay();
}
public void performFly() {
flyBehavior1.fly();
flybehaviour2.fly();
}
public void display() {
System.out.println("I'm a real mallard duck");
}
}
Alternatively, you could use the Decorator Design Pattern (page 88 of
your book).....