OO Design Patterns - Decorator Object-Oriented Programming
Starbuzz Coffee current design Đại học Công nghệ - ĐHQG HN OO Design Pattern
Starbuzz Coffee problem In addition to coffee, customers can ask for condiments like milk, mocha, soy,… then topped with whipped cream How to modify the current system to allow that? Đại học Công nghệ - ĐHQG HN OO Design Pattern
Đại học Công nghệ - ĐHQG HN OO Design Pattern
Đại học Công nghệ - ĐHQG HN Inheritance
Better, but there’re still potential issues What requirements or other factors might change that will impact this design? Price changes for condiments New condiments New beverages What about a double mocha? And ??? Đại học Công nghệ - ĐHQG HN Inheritance
Open-Closed Principle Open to extension: you can create subclasses Closed to modification: don’t modify existing code But be careful! Apply OCP principle EVERYWHERE is wasteful, unnecessary, and can lead to complex, hard to understand code Đại học Công nghệ - ĐHQG HN OO Design Pattern
Decorator Pattern A customer wants a Dark Roast with Mocha and Whip, we’ll: Take a DarkRoast object Decorate it with a Mocha object Decorate it with a Whip object Call the cost() method and rely on delegation to add on the condiment costs. Đại học Công nghệ - ĐHQG HN OO Design Pattern
Đại học Công nghệ - ĐHQG HN OO Design Pattern
Đại học Công nghệ - ĐHQG HN OO Design Pattern
Đại học Công nghệ - ĐHQG HN OO Design Pattern
Đại học Công nghệ - ĐHQG HN OO Design Pattern
Decorating our beverages Đại học Công nghệ - ĐHQG HN OO Design Pattern
Question Why should Beverage be an abstract class instead of an interface? Đại học Công nghệ - ĐHQG HN OO Design Pattern
Question Why should Beverage be an abstract class instead of an interface? Answer: Interface would work just as fine, but the existing code is an abstract class. Don’t alter existing code if it works fine. Đại học Công nghệ - ĐHQG HN OO Design Pattern
Question How to make a double mocha, soy latte with whip? Đại học Công nghệ - ĐHQG HN OO Design Pattern
Realworld Decorator: Java I/O Đại học Công nghệ - ĐHQG HN OO Design Pattern
Đại học Công nghệ - ĐHQG HN OO Design Pattern
OO Design Principles We’ve learned so far Encapsulate what varies Favor composition over inheritance Program to interfaces, not implementations Strive for loosely coupled designs between objects that interact. Open for extension, closed for modification Class is about behavior And more…. in the textbook. Đại học Công nghệ - ĐHQG HN OO Design Pattern