From the course: Programming Foundations: Design Patterns

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Extending behavior with composition

Extending behavior with composition

From the course: Programming Foundations: Design Patterns

Start my 1-month free trial

Extending behavior with composition

- [Instructor] Before we jump into a formal definition of the Decorator pattern, let's first get a conceptual feel for how Decorator works and in particular see how we might use composition to solve our problems. To do that, let's go back to our original beverage design. Now, let's say a customer wants to order DarkRoast with Mocha and Whip. So, let's start simply by instantiating a DarkRoast object, shown here. Let's also call this object our base object, the coffee itself. Next, the customer wants Mocha, so let's create a second object, a Mocha object and wrap it around or compose it with the DarkRoast object. We'll call Mocha a Decorator and as to the hint to the structure of all this, Mocha's type is going to mirror the type of the object that it's composed with. Which, in this case, is a beverage. So, Mocha also has type beverage. Note that means it also has a cost method, so keep that in mind. Now the customer also wants Whip, so let's create a Whip object and wrap it around or…

Contents