1 / 96

Unit 5 Builder

Unit 5 Builder. Summary prepared by Kirk Scott. Design Patterns in Java Chapter 15 Builder. Summary prepared by Kirk Scott. The Introduction Before the Introduction. All patterns occur in some context The book’s example occurs in the context of parsing

blenda
Download Presentation

Unit 5 Builder

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit 5Builder Summary prepared by Kirk Scott

  2. Design Patterns in JavaChapter 15Builder Summary prepared by Kirk Scott

  3. The Introduction Before the Introduction • All patterns occur in some context • The book’s example occurs in the context of parsing • Parsing overall is not a small topic, so explaining the background takes up some time • I also present an example where input comes through a GUI rather than through parsing

  4. Builder • One explanation for the use of the builder class is that at a given time, not all of the information needed (construction parameters) may be available to do construction • Construction parameters may have to be parsed from some input string • Or they may come in from some kind of user interface • Actual construction has to be delayed

  5. Another explanation for using the Builder design pattern is that construction can be moderately complicated in some cases • Instead of cluttering up the class code with these complexities, you want to have the class contain just the normal methods and simple constructors • You can offload the more complex versions of construction into a builder class

  6. Book Definition of Pattern • Book definition: • The intent of the Builder pattern is to move the construction logic for an object outside the class to be instantiated. • Comment mode on: • By definition, construction is being offloaded. • Offloading also makes it possible for actual construction to be delayed.

  7. Ordinary Construction • An ordinary constructor expects all of the construction parameters to be available at the time the constructor is called • For an ordinary constructor: • The construction parameters have to exist • They should be valid/contain valid values

  8. Constructing when not all Parameters are Available • In the book’s parsing example, the construction parameters have to be extracted from a String • Not all parameters will be available up front • The builder is an intermediate object that can hold input values until all are available to construct the base object desired

  9. The Fireworks Reservation Example • The book paints the following scenario: • Suppose reservations for fireworks shows are submitted as text strings like this example: • Date, November 5, Headcount, 250, City, Springfield, DollarsPerHead, 9.95, HasSite, False

  10. The syntax of the input string is clear • Items are separated by commas • The order may be important, or the fact that each value is preceded by a label/variable name may mean that there is flexibility in the order

  11. Why a Builder Might Be Useful • A simple approach to the construction of a reservation object illustrates the potential value of using the builder pattern • Suppose you used a default constructor to construct an empty reservation • Then, as the string was parsed, set methods could be called to set the instance variable values

  12. The shortcoming to this approach is that midway through parsing you may encounter an error, an invalid parameter value, or a missing parameter value • At this point the client code has to be written to handle an error condition like this

  13. Alternatively, you may “save up” construction parameters, but without verifying them • Then you attempt to construct • This can lead to disaster if input parameters are incorrect • You could try to write the constructor code to handle verification

  14. The builder design pattern gets around the potential problems of both of the foregoing scenarios • Parsing and verifying are done before trying to construct • This means you don’t have to try and verify or handle error conditions in client code and you also don’t have to put the verification code into the class constructor

  15. Responsibility • This goes back to responsibility • You don’t want to do ad hoc parsing and verifying in every client program • The client shouldn’t be responsible for the base class • On the other hand, this pattern is a step away from pure responsibility of the base class for itself • The builder pattern gives an organized way of putting the verification logic into a single class that can be re-used, without burdening the base class with these details

  16. The Book’s Example • The UML diagram on the next overhead shows some of the classes that will be needed for the book’s overall design

  17. The example has a Reservation class • This is the base class that is ultimately to be constructed • The example has a ReservationParser class • This class has a builder instance variable • The example has a ReservationBuilder class, which is abstract • Before the example is complete, concrete builder classes will be needed

  18. The abstract ReservationBuilder class shows what all builder classes will have to contain • In particular, it contains an abstract build() method • The build() method contains a call to the constructor Reservation()

  19. The UML diagram illustrates another fundamental thing about the book’s scenario • Not only has construction been offloaded • The get and set methods for the Reservation class are mirrored in the ReservationBuilderclass • Even though not explicitly shown, the mirroring of the set methods tells you that the instance variables have also been mirrored

  20. First you create a builder • Then you call its set methods to set its instance variables, which mirror the base class’s instance variables • The idea is that the construction parameters for a reservation will be fed piecemeal to a builder object by calling the set methods

  21. Then you call the build() method on the builder • The build() method verifies that the builder’s instance variable values are valid as construction parameters for a base class object • If they are OK, the base class constructor will be called with these parameters • Otherwise, an exception will be thrown

  22. Why is the ReservationBuilder Class Abstract? • In general, a simple example scenario could have a concrete ReservationBuilder class with a concrete build() method • However, you may want to build in different ways in different cases • This leads the authors to develop several different builders with different characteristics • The idea is that building can take on a life of its own

  23. Once building takes on a life of its own, the pattern begins to make sense • Each of the different building scenarios is implemented in its own builder class • You’re extracting construction logic from the constructor of the base class and implementing it in a separate class • The class is no longer fully responsible for itself

  24. The alternative is to write constructor code with complex logic for a variety of different cases • The base class begins to become responsible for “too much stuff” • The builder approach is cleaner • Building, although closely related to construction, is not construction itself • The responsibility for verifying construction parameters is encapsulated in separate classes devoted to that

  25. What Does the ReservationParser Class Do in the Example? • Before considering the concrete subclasses of the ReservationBuilder, it’s necessary to examine the role of the ReservationParser in the example • Keep in mind that you need input parameters from somewhere, but that a parser isn’t intrinsically part of the pattern

  26. Calling the parse() method on a ReservationParser object, passing it a String, s, is the first step towards constructing a reservation • The parse() method tries to extract construction parameters for a reservation from the String s • The String s is a comma separated list

  27. The parse() method makes use of a method named split() from the String class • A call to split() takes the form of s.split(“,”) • The call to split() returns an array of Strings, known as tokens, which are the substrings of s which are separated by commas

  28. The parse() method also makes use of formatting and parsing characteristics of the Date class • Among the things that happens with dates is that a month and day are always pushed into the next year so that reservations are for the future, not the past

  29. When constructed, the ReservationParser accepts a reference to a builder object • The parse() method examines the tokens of the input String one-by-one • If they appear to be of the right type, inside the parse() method the set() method for the corresponding Reservation instance variable is called on the builder object

  30. Passing the reference to builder into the parser as a construction parameter allows calls to set() in the parse method to change the builder • Then, after the call to parse(), the call to build() can be made on the changed builder object in the client code • The code for the parse() method is shown beginning on the next overhead

  31. public void parse(String s) throws ParseException • { • String[] tokens = s.split(","); • for(inti = 0; i < tokens.length; i += 2) • { • String type = tokens[i]; • String val = tokens[i + 1]; • if("date".comareToIgnoreCase(type) == 0) • { • Calendar now = Calendar.getInstance(); • DateFormat formatter = DateFormat.getDateInstance(); • Date d = formatter.parse(val + ", “ • + now.get(Calendar.YEAR)); • builder.setDate(ReservationBuilder.futurize(d)); • }

  32. else if("headcount".compareToIgnoreCase(type) == 0) • builder.setHeadCount(Integer.parseInt(val)); • else if("City".compareToIgnoreCase(type) == 0) • builder.setCity(val.trim()); • else if("DollarsPerHead".compareToIgnoreCase(type) == 0) • builder.setDollars(Double.parseDouble(val))); • else if("HasSite".compareToIgnoreCase(type) == 0) • builder.setHasSite(val.equalsIgnoreCase("true"); • /******* Observe that it's a great mystery to me how • the authors can end a sequence of if/else if statements • without a final else, but that's the way the code is • given in the book. *******/ • } • }

  33. What Could Go Wrong with Parsing? • Parsing can go wrong basically if the input String s is flawed • The list might not be correctly comma separated or some of the values might not be of the right type • The parser doesn’t look beyond these kinds of problems

  34. What Do the Individual, Concrete Builder Classes Do? • In general, the task of the individual builders is to build under constraints • Constraints can be things like valid ranges for the values of construction parameters • It is the builder classes that are designed to implement those kinds of constraints and be more or less forgiving of faulty input

  35. In other words, given the construction parameters extracted from the input String by the parser, what can you do with them? • Suppose that every reservation had to have a non-null date and city • Or suppose, at a more fine-grained level, there have to be at least 25 people in the audience and the total bill has to be at least $495.95.

  36. In support of these constraints, a builder class might contain these declarations: • public abstract class ReservationBuilder • { • public static final int MINHEAD = 25; • public static final Dollars MINTOTAL = new Dollars(495.95); • // … • }

  37. Varying checks for validity can then be put into the build() method of the builder classes rather than the base class (or the parser) • The UML diagram on the following overhead shows two concrete subclasses of the abstract class ReservationBuilder, one a forgiving builder and one an unforgiving builder

  38. In the ReservationBuilder classes the build() method either returns a reference to a newly constructed Reservation object • Or it throws an exception, in this case a BuilderException • The UnforgivingBuilder and the ForgivingBuilder differ according to the conditions under which they throw a BuilderException

  39. Before considering the implementation of one of the builder classes, the book shows some code illustrating how the parser and a builder would be related • It is given on the next overhead • It will be followed by commentary

  40. public class ShowUnforgiving • { • public static void main(String[] args) • { • String sample = “Date, November 5, Headcount, 250” + “City, Springfield, DollarsPerHead, 9.95” + “HasSite, False”; • ReservationBuilder builder = new UnforgivingBuilder(); • try • { • new ReservationParser(builder).parse(sample); • Reservation res = builder.build(); • System.out.println(“Unforgiving builder: “ + res); • } • catch(Exception e) • { • Systemout.println(e.getMessage()); • } • } • }

  41. In the client, the builder is created up front • The parser is created, passing in the builder • parse() is then called on the parser, passing in the string • Recall that inside the parse() method the set methods are called on the builder object one-by-one

  42. After the parsing is done, build() is called on the builder • If the parameters weren’t right, the build() method will throw an exception • If the parameters were all right, the build() method will construct a reservation object and return a reference to it • The end result of this collection of interrelated classes is that actual construction is delayed until the construction parameters are verified

  43. These are the critical lines of code: • ReservationBuilder builder = new UnforgivingBuilder(); • try • { • new ReservationParser(builder).parse(sample); • Reservation res = builder.build(); • System.out.println(“Unforgiving builder: “ + res); • Because the sample string is OK, this code will simply print out the message “Unforgiving builder: ” followed by the successfully built reservation

  44. Challenge 15.2 • “The build() method of the UnforgivingBuilder class thows a BuilderException if the date or city is null, if the headcount is too low, or if the total cost of the proposed reservation is too low. • Write the code for the build() method according to these specifications.”

  45. Comment mode on: • In essence the build() method will turn out to be a bunch of if statements potentially followed by construction of the desired reservation object.

  46. Solution 15.2 • “The build() method of UnforgivingBuilder throws an exception if any attribute is invalid and otherwise returns a valid Reservation object. • Here is one implementation:” • [See next overhead.]

  47. public Reservation build() throws BuilderException • { • if(date == null) • throw new BuilderException(“Valid date not found”); • if(city == null) • throw new BuilderException(“Valid city not found”); • if(headcount < MINHEAD) • throw new BuilderException(“Minimum headcount is ” + MINHEAD); • if(dollarsPerHead.times(headcount).isLessThan(MINTOTAL)) • throw new BuilderException(“Minimum total cost is ” + MINTOTAL); • return new Reservation(date, headCount, city, dollarsPerHead, hasSite); • }

  48. Solution 15.2, continued. • “The code checks that date and city values are set and checks that headcount and dollars/head values are acceptable. • The ReservationBuildersuperclass defines the constants MINHEAD and MINTOTAL. • If the builder encounters no problems, it returns a valid Reservation object.”

More Related