tailieunhanh - head first design patterns phần 9

Vì vậy, đây là những gì chúng ta sẽ làm thay thế: chúng ta sẽ bắt đầu với một nước giải khát và "trang trí" với các gia vị trong thời gian chạy. Ví dụ, nếu khách hàng muốn một Roast tối với Mocha và Whip, sau đó chúng tôi sẽ:Được rồi, đủ "Câu lạc bộ Thiết kế Object Oriented." Chúng tôi có vấn đề thực sự ở đây! Chúng tôi | compound patterns 0 Now let s give this a quick run. This time when we run the simulator the list of objects passed to the simulateO method includes a Goose wrapped in a duck adapter. The result We should see some honking There s the ỳooitỊ N ow the oose óan uaek with the rest of the Dudes Ị Quackologists are fascinated by all aspects of Quackable behavior. One thing Quackologists have always wanted to study is the total number of quacks made by a flock of ducks. How can we add the ability to count duck quacks without having to change the duck classes Can you think of a pattern that would help J- Brewer Park Ranker and uddeoloíỷst you are here 505 duck decorator Were going to make those Quackologists happy and give them some quack counts. How Let s create a decorator that gives the ducks some new behavior the behavior of counting by wrapping them with a decorator object. We won t have to change the buck code at all. ộuackCounter is a decorator public class QuackCounter implements Quackable I Quackable duck static int numberOfQuacks . Like with Adapter we need to implement -the tarjet interface Vlt it. jot an instance variable to hold on to the juacker were decor atinj. io we ll use a static public QuackCounter Quackable duck - duck variable to keep track. public void quack numberOfQuacks We jet the reference to the ộvackable were decoratinj in the Constructor- When uackO is called we delejate the call to the uackab e were dcCorat m public static int getQuacksO return numberOfQuacks We re addinj one other method to the decorator. This static method just returns the number of quacks that have occurred in all ộuackables. 506 Chapter 12 compound patterns 9 We need to update the simulator to create decorated ducks. Now we must wrap each Quackable object we instantiate in a QuackCounter decorator. If we don t well have ducks running around making uncounted quacks. public class Ducksimulator public static void main String args Ducksimulator simulator