tailieunhanh - head first design patterns phần 2

Sau khi thêm một tham chiếu đến , bạn phải nhập khẩu và không gian tên khác có liên quan, tùy thuộc vào các lớp ứng dụng của bạn sẽ sử dụng. Để bây giờ, chúng ta sẽ nhập khẩu các không gian tên và . Chúng tôi bổ sung thêm hai dòng sau vào đầu của lớp của chúng tôi: | intro to Design Patterns Testing the Puck code continued. 0 Type and compile the QuackBehavior interface and the three behavior implementation classes and . public interface QuackBehavior public void quack public class Quack implements QuackBehavior public void quack 0 Quack public class MuteQuack implements QuackBehavior public void quack silence public class Squeak implements QuackBehavior public void quack Squeak I 1 0 Type and compile the test class . public class MiniDucksimulator public static void main String args Duck mallard new MallardDuck MallardP k s inherited - TK S Jx then delegates to 1 X I 1 X 0 Run the code Tke. e do tìe d ns 8 Pinaow Hrtp mHerita feformF y java MiniDuckSimulator Quack I m flying you are here 19 ducks with dynamic behavior Setting behavior dynamically What a shame to have all this dynamic talent built into our ducks and not be using it Imagine you want to set the duck s behavior type through a setter method on the duck subclass rather than by instantiating it in the duck s constructor. 0 Char Modi o Add two new methods to the Duck class public void setFlyBehavior FlyBehavior fb flyBehavior fb qb Duck public void setQuackBehavior QuackBehavior quackBehavior qb 1 We can call these methods-anytime we want to change the behavior of a duck rtn the fly. J swim display perforrnQuackf performFIyO setFlyBehavkxQ setQuackBehavioự II OTHER duck-like methods. FlyBehavkx flyBehaviof QuackBehaviof quackBehavior public publ. Di editor note gratuitous pun - fix Q Make a new Duck type . public class ModelDuck extends Duck public ModelDuckO flyBehavior new FlyNoWayO quackBehavior new Quack0 1 a xai public void display 0 I m a model duck 1 Q Make a new FlyBehavior type That s okay we re creating a . F d