0% found this document useful (0 votes)
21 views

Setting Behavior Dynamically: 1. Add Two New Methods To The Duck Class

The document describes how to dynamically set the behavior of a Duck object at runtime. It involves: 1) Adding methods to the Duck class to set its fly and quack behaviors. 2) Creating a ModelDuck class that initially cannot fly and quacks normally. 3) Defining a new FlyBehavior. 4) Creating a test that sets the ModelDuck's fly behavior to use rockets, allowing it to fly in a new way.

Uploaded by

api-251901021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Setting Behavior Dynamically: 1. Add Two New Methods To The Duck Class

The document describes how to dynamically set the behavior of a Duck object at runtime. It involves: 1) Adding methods to the Duck class to set its fly and quack behaviors. 2) Creating a ModelDuck class that initially cannot fly and quacks normally. 3) Defining a new FlyBehavior. 4) Creating a test that sets the ModelDuck's fly behavior to use rockets, allowing it to fly in a new way.

Uploaded by

api-251901021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Setting behavior dynamically

1. Add two new methods to the Duck class


public void setFlyBehavior (FlyBehavior fb) { flyBehavior = fb; } public void setQuackBehavior(QuackBehavior qb) { quackBehavior = qb; }

2. Make a new Duck type (ModelDuck.java)


public class ModelDuck extends Duck { public ModelDuck() { flyBehavior = new FlyNoWay(); quackBehavior = new Quack(); } public void display() { System.out.println("I'm a model duck"); } }

3. Make a new FlyBehavior type (FlyRocketPowered.java)


public class FlyRocketPowered implements FlyBehavior { public void fly() { System.out.println("I'm flying with a rocket"); } }

4. Change the test class (MiniDuckSimulator.java), add the ModelDuck, and make the ModelDuck rocket-enabled
public class MiniDuckSimulator1 { public static void main(String[] args) { Duck mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); Duck model = new ModelDuck(); model.performFly(); model.setFlyBehavior(new FlyRocketPowered()); model.performFly(); } }

5. Run the code!


> java MiniDuckSimulator1 Quack I'm flying!! I can't fly I'm flying with a rocket

You might also like