TAILIEUCHUNG - head first design patterns phần 3

Đượ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? Starbuzz cà phê? Bạn có nghĩ rằng bạn có thể sử dụng một số nguyên tắc thiết kế để thực sự giúp chúng tôi? Đi một đối tượng DarkRoast trang trí nó với một đối tượng Mocha Trang trí với một đối tượng Whip Gọi chi phí () và dựa trên đoàn để thêm vào các chi phí gia vị | meet the decorator pattern Okay enough of the Object Oriented Design Club. We have real problems here Remember us Starbuzz Coffee Do you think you could use Moot tho Ponnratnr PattorM ksome of those . design PrinciPles to Meet the izecuratur raiiern actually help us . Okay we ve seen that representing our beverage plus condiment pricing scheme with inheritance has not worked out very well - we get class explosions rigid designs or we add functionality to the base class that isn t appropriate for some of the subclasses. So here s what we ll do instead we ll start with a beverage and decorate it with the condiments at runtime. For example if the customer wants a Dark Roast with Mocha and Whip then we ll 9 Take a DarkRoast object 2 Decorate it with a Mocha object r3 Decorate it with a Whip object r4 Call the cost method and rely on delegation to add on the condiment costs Okay but how do you decorate an object and how does delegation come into this A hint think of decorator objects as wrappers. Let s see how this works. 88 Chapter 3 the decorator pattern Constructing a drink order with Decorators We start with our DarkRoast object. I Ti avkR. ast that has Rememb 1 Beverage art J kkat tornotes method a tost c ke dr -the The customer wants Mocha so we create a Mocha object and wrap it around the DarkRoast. is a decorator. Its a pc - ir is -the same type- Beverage - 3 The customer also wants Whip so we create a Whip decorator and wrap Mocha with it. cost cost cost 0arkRo Whip is a decorator so it also mirrors DarkRoast s type and includes a cost method. So a DarkRoast wrapped in Mocha and Whip is still a Beverage and we can do anything with it we can do with a DarkRoast including call its cost method. you are here 4 89 decorator characteristics 4 Now it s time to compute the cost for the customer. We do this by calling cost on the outermost decorator Whip and Whip is going to delegate computing the cost to the objects it decorates. Once it gets a cost it will add on the

Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.