Presentation is loading. Please wait.

Presentation is loading. Please wait.

Builder Introduction. Intent Separate the construction of a complex object from its representation so that the same construction process can create different.

Similar presentations


Presentation on theme: "Builder Introduction. Intent Separate the construction of a complex object from its representation so that the same construction process can create different."— Presentation transcript:

1 Builder Introduction

2 Intent Separate the construction of a complex object from its representation so that the same construction process can create different representations ▫Defines an instance for creating an object but letting subclasses decide which class to instantiate ▫Refers to the newly created object through a common interface 2

3 Motivation The more complex an application is the complexity of classes and objects used increases Complex objects are made of parts produced by other objects that need special care when being built An application might need a mechanism for building complex objects that is independent from the ones that make up the object 3

4 Motivation (Cont’d) This pattern allows a client object to construct a complex object by specifying only its type and content, being shielded from the details related to the object’s representation This way the construction process can be used to create different representations The logic of this process is isolated from the actual steps used in creating the complex object, so the process can be used again to create a different object from the same set of simple objects as the first one 4

5 Motivation (Cont’d) A reader for the RTF document format should be able to convert it to many text formats. The reader might convert RTF documents into plain ASCII text or into a text widget that can be edited interactively. The problem, however, is that the number of possible conversions is open-ended. So it is not easy to add a new conversion without modifying the reader. A solution is to configure the RTFReader class with a TextConverter object that converts RTF to another textual representation. As the RTFReader parses the RTF document, it uses the TextConverter to perform the conversion. Whenever the RTFReader recognizes an RTF token (either plain text or an RTF control word), it issues a request to the TextConverter to convert the token. TextConverter objects are responsible both for performing the data conversion and for representing the token in a particular format. 5

6 Motivation (Cont’d) Subclasses of TextConverter specialize in different conversions and formats. For example, an ASCIIConverter ignores requests to convert anything except plain text. A TeXConverter, on the other hand, will implement operations for all requests in order to produce a TeX representation that captures all the stylistic information in the text. A TextWidgetConverter will produce a complex user interface object that lets the user see and edit the text. 6

7 Motivation (Cont’d) 7

8 Each kind of converter class takes the mechanism for creating and assembling a complex object and puts it behind an abstract interface. The converter is separate from the reader, which is responsible for parsing an RTF document. The Builder pattern captures all these relationships. Each converter class is called a builder in the pattern, and the reader is called the director. Applied to this example, the Builder pattern separates the algorithm for interpreting a textual format (that is, the parser for RTF documents) from how a converted format gets created and represented. This lets us reuse the RTFReader's parsing algorithm to create different text representations from RTF documents—just configure the RTFReader with different subclasses of TextConverter. 8

9 Applicability Use the Builder pattern when ▫the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled. ▫the construction process must allow different representations for the object that's constructed. 9

10 Structure 10

11 Participants Builder (TextConverter) ▫specifies an abstract interface for creating parts of a Product object. ConcreteBuilder (ASCIIConverter, TeXConverter, TextWidgetConverter) ▫constructs and assembles parts of the product by implementing the Builder interface. ▫defines and keeps track of the representation it creates. ▫provides an interface for retrieving the product (e.g., GetASCIIText, GetTextWidget). Director (RTFReader) ▫constructs an object using the Builder interface. Product (ASCIIText, TeXText, TextWidget) ▫represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled. ▫includes classes that define the constituent parts, including interfaces for assembling the parts into the final result. 11

12 Collaborations The client creates the Director object and configures it with the desired Builder object. Director notifies the builder whenever a part of the product should be built. Builder handles requests from the director and adds parts to the product. The client retrieves the product from the builder. 12

13 Collaborations The following interaction diagram illustrates how Builder and Director cooperate with a client. 13

14 Example 14

15 Consequences It lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product. It also hides how the product gets assembled. Because the product is constructed through an abstract interface, all you have to do to change the product's internal representation is define a new kind of builder. It isolates code for construction and representation. The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented. Clients needn't know anything about the classes that define the product's internal structure; such classes don't appear in Builder's interface. 15

16 Consequences Each ConcreteBuilder contains all the code to create and assemble a particular kind of product. The code is written once; then different Directors can reuse it to build Product variants from the same set of parts. In the earlier RTF example, we could define a reader for a format other than RTF, say, an SGMLReader, and use the same TextConverters to generate ASCIIText, TeXText, and TextWidget renditions of SGML documents. It gives you finer control over the construction process. Unlike creational patterns that construct products in one shot, the Builder pattern constructs the product step by step under the director's control. Only when the product is finished does the director retrieve it from the builder. Hence the Builder interface reflects the process of constructing the product more than other creational patterns. This gives you finer control over the construction process and consequently the internal structure of the resulting product. 16

17 Implementation Typically there's an abstract Builder class that defines an operation for each component that a director may ask it to create. The operations do nothing by default. A ConcreteBuilder class overrides operations for components it's interested in creating. Assembly and construction interface. Builders construct their products in step-by-step fashion. Therefore the Builder class interface must be general enough to allow the construction of products for all kinds of concrete builders. A key design issue concerns the model for the construction and assembly process. A model where the results of construction requests are simply appended to the product is usually sufficient. In the RTF example, the builder converts and appends the next token to the text it has converted so far. 17

18 Implementation But sometimes you might need access to parts of the product constructed earlier. Tree structures such as parse trees that are built bottom-up are a good example. In that case, the builder would return child nodes to the director, which then would pass them back to the builder to build the parent nodes. 18

19 Implementation Why no abstract class for products? In the common case, the products produced by the concrete builders differ so greatly in their representation that there is little gain from giving different products a common parent class. In the RTF example, the ASCIIText and the TextWidget objects are unlikely to have a common interface, nor do they need one. Because the client usually configures the director with the proper concrete builder, the client is in a position to know which concrete subclass of Builder is in use and handle its products accordingly. 19

20 Assignment#1 1.Make groups of 3 people (not more not less) 2.Implement Builder Pattern in C# 3.Should be submitted in next class on 30Oct2013 4.Write one page report on the problem and its solution achieved by Builder pattern 20

21 Decorator Introduction

22 Decorator Pattern The Decorator Pattern provides a powerful mechanism for adding new behaviors to an object at run-time The mechanism is based on the notion of “wrapping” which is just a fancy way of saying “delegation” but with the added twist that the delegator and the delegate both implement the same interface 22

23 Decorator Pattern You start with object A that implements abstract type X You then create object B that also implements abstract type X You pass A into B’s constructor and then pass B to A’s client The client thinks its talking to A but its actually talking to B B’s methods augment or add to A’s methods to provide new behavior 23

24 Decorator Pattern The decorator pattern provides yet another way in which a class’s runtime behavior can be extended without requiring modification to the class “Starbuzz Coffee” example clearly demonstrates why inheritance can get you into trouble and why delegation/composition provides greater run-time flexibility 24

25 Welcome to Starbuzz Coffee Starbuzz Coffee has made a name for itself as the fastest growing coffee shop around. If you’ve seen one on your local corner, look across the street; you’ll see another one Because they’ve grown so quickly, they’re scrambling to update their ordering systems to match their beverage offerings 25

26 Initial Design of Classes for Starbuzz 26

27 Initial Design of Classes for Starbuzz Beverage is an abstract class, sub-classed by all beverages offered in the coffee shop The cost() method is abstract; sub-classes need to define their own implementation The description instance variable is set in each subclass and holds a description of the beverage, like “Most Excellent Dark Roast” The getDescription() method returns the description Each subclass implements cost() to return the cost of the beverage 27

28 Add Condiments to Regular Beverages In addition to your coffee, you can also ask for several condiments like steamed milk, soy, and mocha (otherwise known as chocolate), and have it all topped off with whipped milk. Starbuzz charges a bit for each of these, so they really need to get them built into their order system What would the class structure look like now? 28

29 29

30 Alternate Approach Why do we need all these classes? Can’t we just use instance variables and inheritance in the super-class to keep track of the condiments? Lets Try it out… Let’s start with the Beverage base class and add instance variables to represent whether or not each beverage has milk, soy, mocha and whip 30

31 31

32 Steps in Alternate Approach We will add new boolean values for each condiment Now we’ll implement cost() in Beverage (instead of keeping it abstract), so that it can calculate the costs associated with the condiments for a particular beverage instance. Subclasses will still override cost(), but they will also invoke the super version so that they can calculate the total cost of the basic beverage plus the costs of the added condiments The get() and set() methods would read and set the values of the condiments. 32

33 Steps in Alternate Method The super-class cost() will calculate the costs for all of the condiments, while the overridden cost() in the subclasses will extend that functionality to include costs for that specific beverage type. Each cost() method needs to compute the cost of the beverage and then add in the condiments by calling the super-class implementation of cost(). What’s wrong with this approach? 33

34 Issues with Alternate Approach You can see some potential problems with this approach by thinking about how the design might need to change in the future. Price changes for condiments will force us to alter existing code New condiments will force us to add new methods and alter the cost method in the super-class We may have new beverages. For some of these beverages (iced tea?), the condiments may not be appropriate, yet the Tea subclass will still inherit methods like hasWhip() 34

35 The Open-Closed Principle Classes should be open for extension, but closed for modification Our goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code. We can get designs that are resilient to change and flexible enough to take on new functionality to meet changing requirements We will study the impact of using Decorator Pattern on Starbuzz example in our next class 35


Download ppt "Builder Introduction. Intent Separate the construction of a complex object from its representation so that the same construction process can create different."

Similar presentations


Ads by Google