Design Patterns in Java Chapter 4 Façade

106
Design Patterns in Java Chapter 4 Façade Summary prepared by Kirk Scott 1

description

Design Patterns in Java Chapter 4 Façade. Summary prepared by Kirk Scott. Preliminary Note. This book takes the trouble to try and provide concrete examples This is a great benefit, and at the same time this approach has a shortcoming - PowerPoint PPT Presentation

Transcript of Design Patterns in Java Chapter 4 Façade

Page 1: Design Patterns in Java Chapter 4 Façade

1

Design Patterns in JavaChapter 4

Façade

Summary prepared by Kirk Scott

Page 2: Design Patterns in Java Chapter 4 Façade

2

Preliminary Note

• This book takes the trouble to try and provide concrete examples

• This is a great benefit, and at the same time this approach has a shortcoming

• The shortcoming is that any applied example will have aspects that are not central to the topic at hand which have to be explained in order to understand the example

• At various points in these overheads it will be necessary to dwell on these other aspects before being able to concentrate on the design pattern in question

Page 3: Design Patterns in Java Chapter 4 Façade

3

Façade

• The book starts with a review of the supposed benefits of object-oriented code development

• The idea is that toolkits of classes are developed, and then application programs can be written which largely depend on the functionality implemented in the toolkits

• In the broadest sense, you might think of the Java API as a toolkit

Page 4: Design Patterns in Java Chapter 4 Façade

4

• Taking that broad of a point of view illustrates one of the shortcomings of this approach

• If the toolkit has too much in it to fully understand, how do you know what features to use or where to start when trying to use to implement an application?

• The authors suggest that an IDE might help isolate a programmer from toolkit complexity, while still making the toolkit available for use

Page 5: Design Patterns in Java Chapter 4 Façade

5

• However, this implies taking the trouble to learn the IDE

• Also, the authors concede that one result of this is that the IDE “automatically” generates a bunch of code for the application programmer—which the programmer may not understand

• It’s bad enough when you don’t understand the toolkit

• It’s may be worse when you don’t understand what is ostensibly your own code

Page 6: Design Patterns in Java Chapter 4 Façade

6

• The façade design pattern is an approach to managing the complexity of a toolkit

• The book describes a façade as a “small amount” of code which provides a typical, no-frills usage of the classes in a class library

• It expands this description by saying that a façade is class with a level of functionality between a toolkit and an application

• This class offers simplified usage of the classes in a package or subsystem

Page 7: Design Patterns in Java Chapter 4 Façade

7

• The book states the intent of the façade pattern in this way

• The intent of the Façade pattern is to provide an interface that makes a subsystem easy to use

Page 8: Design Patterns in Java Chapter 4 Façade

8

• The book will take two approaches to illustrating what a façade is

• The first approach is to point out a class in the Java API which it says meets the definition of a façade

• This Java API class is not simple• It provides an example of the idea where it

would be impossible to delve into everything that went into its implementation

Page 9: Design Patterns in Java Chapter 4 Façade

9

• The second approach will be to give a concrete example including code

• Although this example doesn’t really show the creation of a façade for a toolkit, it illustrates a use of the design pattern in software development that may be of even greater practical value

• It is based on the idea that you may have a programming problem which will involve several different functionalities and will require several different classes to implement

Page 10: Design Patterns in Java Chapter 4 Façade

10

• At a very basic level, the first design question is, which classes will you have and which functionalities belong in which classes

• A secondary, and equally realistic way of looking at this is that you made those design decisions and you don’t like the resulting code

• The façade pattern can be used as a model for abstracting out certain functionalities into one class (the façade) and reorganizing the remaining functionalities in a set of classes that is more logical or convenient

Page 11: Design Patterns in Java Chapter 4 Façade

11

Facades, Utilities, and Demos

• If a class which fits the intent of the Façade design pattern consists entirely of static methods, then it is appropriate to refer to it as a utility

• The book observes that the limitation this imposes is that you would be prevented from overriding static methods in future subclasses

Page 12: Design Patterns in Java Chapter 4 Façade

12

• This is another one of those book insights where my reaction is, “Why would you even have considered overriding static methods? I never even thought of that before.”

• Maybe a more useful way of stating this is that if you do develop a façade, containing non-static methods, in theory you could extend the façade class to a different situation and override the methods in it if necessary

Page 13: Design Patterns in Java Chapter 4 Façade

13

• Next the book introduces the term demo• This is defined as an example that shows how to

use a class or subsystem• Demos provide much of the same information or

value to the programmer as a façade, but obviously they are not exactly the same thing

• The difference can expressed in terms of the intent or in terms of the use to which they can be put

Page 14: Design Patterns in Java Chapter 4 Façade

14

• Challenge 4.1• Write down two differences between a demo

and a façade.

Page 15: Design Patterns in Java Chapter 4 Façade

15

• Solution 4.1• Some differences to note between demos and

facades are as follows.– A demo is usually a stand-alone application; a façade is

usually not.– A demo usually includes sample data; a façade does not.– A façade is usually configurable; a demo is not– A façade is intended for reuse; a demo is not– A façade is intended for use in production; a demo is not

Page 16: Design Patterns in Java Chapter 4 Façade

16

• The book uses the JOptionPane class from the Java API as an example of a façade

• If you look in the API documentation, this class has dozens of methods of its own and it inherits literally hundreds of others

• It is in the javax.swing package, which implies that it can be used in the writing of graphical user interface code

• God only knows how many discrete elements of the swing package the JOptionPane class is based on, or provides a way of using

Page 17: Design Patterns in Java Chapter 4 Façade

17

• The book provides example code for an application that pops up a confirm dialog box

• It so happens that this is done with a static method call

• There is no reason to look at the complete code

Page 18: Design Patterns in Java Chapter 4 Façade

18

• The one line of code in question looks like this• option = JOptionPane.showConfirmDialog(…);

• This is what the code produces on the screen

Page 19: Design Patterns in Java Chapter 4 Façade

19

Page 20: Design Patterns in Java Chapter 4 Façade

20

• The use of the JOptionPane should not be foreign to you, because it was used in unit 17 of CS 202

• In the code for Echo1.java there was a line of code like this

• inputString = JOptionPane.showInputDialog(…);

• This is what the code produces on the screen

Page 21: Design Patterns in Java Chapter 4 Façade

21

Page 22: Design Patterns in Java Chapter 4 Façade

22

• Challenge 4.2• The JOptionPane class makes it easy to display

a dialog. Say whether this class is a façade, a utility, or a demo, and justify your answer.

Page 23: Design Patterns in Java Chapter 4 Façade

23

• Solution 4.2• Note that it makes for poor reading on

overheads, but I have been making it a practice to give the challenge solutions in their entirety, and will do so again here

Page 24: Design Patterns in Java Chapter 4 Façade

24

• The JOptionPane class is one of the few examples of a Façade in the Java class libraries.

• It is production worthy, configurable, and designed for reuse.• Above all else, the JOptionPane class fulfills the intent of the

Façade pattern by providing a simple interface that makes it easy to use the JDialog class.

• You might argue that a façade simplifies a “subsystem” and that the solitary Jdialog class does not qualify as a subsystem.

• But it is exactly the richness of this class’s features that make a façade valuable.

Page 25: Design Patterns in Java Chapter 4 Façade

25

• Sun Microsystems bundles many demos in with the JDK.

• However, these classes are never part of the Java class libraries.

• That is, these classes do not appear in packages with a java prefix.

• A façade may belong in the Java class libraries, but demos do not.

Page 26: Design Patterns in Java Chapter 4 Façade

26

• JOptionPane has dozens of static methods that effectively make it a utility as well as a façade.

• Strictly speaking, though, it does not meet the UML definition of a utility, which requires it to possess solely static methods.

Page 27: Design Patterns in Java Chapter 4 Façade

27

• Challenge 4.3• Few facades appear in the Java class libraries.

Why is that?

Page 28: Design Patterns in Java Chapter 4 Façade

28

• Here are a few reasonable but opposing views regarding the paucity of facades in the Java class libraries.– As a Java developer, you are well advised to

develop a thorough knowledge of the tools in the library. Facades necessarily limit the way you might apply any system. They would be a distracting and potentially misleading element of the class libraries in which they might appear.

Page 29: Design Patterns in Java Chapter 4 Façade

29

– A façade lies somewhere between the richness of a toolkit and the specificity of a particular application. To create a façade requires some notion of the type of applications it will support. This predictability is impossible given the huge and diverse audience of the Java class libraries.

– The scarcity of facades in the class librarires is a weakness. Adding more facades would be a big help.

Page 30: Design Patterns in Java Chapter 4 Façade

30

Refactoring to Façade will be Delayed

• The book next takes up the topic of restructuring a given design using the façade pattern as a model

• Before finishing with that discussion, the book brings up the topic of parametric equations, which are used in the example code

• I think it makes more sense to dispense with the parametric equations first, and then deal with refactoring to façade without interruptions

Page 31: Design Patterns in Java Chapter 4 Façade

31

Parametric Equations

• One example of a case where parametric equations would be useful is when you are interested in plotting a mathematical relationship which isn’t expressed as a function

• For example, in Java, graphical objects are generally determined by (x, y, w, h)—in other words, their location is specificed by an (x, y) pair

Page 32: Design Patterns in Java Chapter 4 Façade

32

• The (x, y) equation for the circle centered at the origin with radius 1 is x2 + y2 = 1.

• If you solve for y, you get y = ±√(1 – x2), which is not a function

• However, if you convert to polar coordinates, for a circle of radius r, for any angle θ (consider the range 0 to 2π), these relationships hold:– sin = y / r– cos = x / r

Page 33: Design Patterns in Java Chapter 4 Façade

33

• Solving for x and y gives:– y = r sin θ– x = r cos θ

• Polar coordinates arise as a natural alternative to Cartesian coordinates

• When presented as given here, they illustrate parameterization

• x and y are expressed in terms of a constant r, and a variable, or parameter, θ, and the expressions for x and y are functional in θ

• There is no confusion about ± values

Page 34: Design Patterns in Java Chapter 4 Façade

34

• Converting a given equation to a parametric form can also be useful even if the equation is already a function

• Consider some of the challenges of representing a mathematical function using the simple graphical capabilities of Java

Page 35: Design Patterns in Java Chapter 4 Façade

35

• A. You have to match up the actual width of the display panel in Java with the range of values x takes on in the function of interest

• B. You have to do the same for y.• C. Also, you have to deal with the fact that in

Cartesian coordinates, the positive y axis points up, while in Java, the positive y axis points down

Page 36: Design Patterns in Java Chapter 4 Façade

36

• By parameterizing an equation it is possible arrive at expressions for x and y that separately take into account the width and height of the display panel and the inversion of y

• In general, this means that code can be written so that w and h themselves variables or input parameters to methods

• This means that code for graphing can accommodate changes in w or h, namely, the dimensions of the display panel

Page 37: Design Patterns in Java Chapter 4 Façade

37

• The book’s example code involves displaying the trajectory of a shell

• This is a projectile that is shot without any propellant of its own (it’s not a rocket)

• If air resistance and wind are ignored, and if the shell doesn’t explode in mid-air and returns to earth, its flight path is a simple parabola

Page 38: Design Patterns in Java Chapter 4 Façade

38

Page 39: Design Patterns in Java Chapter 4 Façade

39

• The book empirically derives some parametric equations for this scenario

• In other words, it approaches the problem by example, using some implicit rules of thumb

• It doesn’t go into any deep theory about parametric equations

• The point is that the example code is implemented using the parametric equations that are derived

Page 40: Design Patterns in Java Chapter 4 Façade

40

• The first task in parameterizing is to decide on a parameter

• In many physical cases it is customary to use the variable t, denoting time

• In practice, t might range from some given starting time to some given ending time

• In this example, it may be thought of as representing time—but not clock time

Page 41: Design Patterns in Java Chapter 4 Façade

41

• When parameterizing for the purposes of graphical display, it is useful have t start at 0 and end at 1

• Then any value of t between 0 and 1 represents the proportion of time that has passed between the beginning and the end of some physical process

• It is not really necessary to think of this as time at all• It can also simply be regarded as a useful

mathematical convenience and nothing more

Page 42: Design Patterns in Java Chapter 4 Façade

42

• Consider the x axis for a function and for display first

• It runs positive from left to right in both Java and in Cartesian coordinates

• The only aspect of parameterization that has to be taken care of for x is to make the range of values it takes on correspond to the amount of time that has passed—or, more importantly, to the width of the display panel

Page 43: Design Patterns in Java Chapter 4 Façade

43

• The book simply gives this parametric equation for x, which satisfies this requirement:

• x = w * t• Clearly, as the value of t goes from 0 to 1, the

value of x goes from 0 to w.

Page 44: Design Patterns in Java Chapter 4 Façade

44

• Taking care of y involves a few more steps• In general, a parabola has a quadratic

equation of the general form y = x2.• However, if you refer to the diagram given

earlier, unlike simple parabolas as initially illustrated in math textbooks, the vertex of a flight path parabola is not at the origin, and the parabola does not open upward

Page 45: Design Patterns in Java Chapter 4 Façade

45

• The parabola of interest has its vertex at the top center of the display panel, and the parabola opens downward

• So the next challenge is to express y in terms of the parameter t

• The first empirical observation that the book makes is that if the vertex appears at the midpoint of the panel, that would correspond to half of w, and in terms of t, it would correspond to half of t

Page 46: Design Patterns in Java Chapter 4 Façade

46

• This parametric equation for y has the vertex in the middle:

• y = (t – .5)(t - .5)• When t = .5, y = 0• When t = 0 or 1, y = (.5)(.5) = .25• So far, so good• Not only is the vertex in the middle, but this result

is convenient for a parabola that opens downward

Page 47: Design Patterns in Java Chapter 4 Façade

47

• The next, intermediate step, is to normalize the maximum value attained by y to 1

• To do this, you introduce a constant to offset the product giving a maximum value of .25

• In other words, you introduce a factor of 4 into the parametric equation:

• y = 4(t - .5)(t - .5)

Page 48: Design Patterns in Java Chapter 4 Façade

48

• Now that the maximum value of y has been normalized to 1, it’s easy to include h as a variable so that the maximum value is h:

• y = 4h(t - .5)(t - .5)• Together, then, these are the parametric

equations:• w = wt• y = 4h(t - .5)(t - .5)

Page 49: Design Patterns in Java Chapter 4 Façade

49

• Keep in mind that although the parameter in the equations is t

• This defines the quadratic relationship between x and y

• The shape of the parabola as graphed will depend on the constant 4 and the variables w and h

Page 50: Design Patterns in Java Chapter 4 Façade

50

• The parameterization of a parabola as shown here is used in the implementation of the original, un-refactored example code given by the book

• It is also used in the new code which results from refactoring using the Façade design pattern

• That is why parameterization has been described here, so that there’s no mystery about how the graphing is being accomplished

Page 51: Design Patterns in Java Chapter 4 Façade

51

Refactoring to Facade

• The book reiterates that facades can arise out of application development

• It may be possible to analyze, or re-analyze a situation where it is desirable to separate functionality into different classes

• One class, a façade, may provide simplified access to the functionality of other classes, the subsystem

Page 52: Design Patterns in Java Chapter 4 Façade

52

• The book’s example is based on the restructuring or refactoring idea

• An original design and code are given, which are not highly desirable

• Then a better design is developed using the façade design pattern

• Following is the UML diagram for a monolithic class that shows the flight path of a shell

Page 53: Design Patterns in Java Chapter 4 Façade

53

Page 54: Design Patterns in Java Chapter 4 Façade

54

• The book identifies three main purposes in the class

• Not surprisingly these purposes are reflected in the methods it contains

• Logically, these purposes can be described as:– To act as a panel that displays a flight path– To act as a complete application, wrapping the

panel in a titled border and displaying it– To calculate the parabolic flight path

Page 55: Design Patterns in Java Chapter 4 Façade

55

• On the one hand, from a design point of view, you might simply object to having three distinctly identifiable purposes to a single class

• That may or may not be a big problem• The book also points out that such code would

have been developed before there were standards for graphical display that were supposed to apply across the code base

Page 56: Design Patterns in Java Chapter 4 Façade

56

• The idea they’re leading to is that the graphics standards could be implemented as a subsystem or toolkit that all graphical applications would use

• Then the specific problem at hand, of displaying a parabola, could be abstracted out

• Also, a separate façade class could be developed so that it was easy to use the graphical standards

Page 57: Design Patterns in Java Chapter 4 Façade

57

• What follows is a presentation and discussion of the code as given in the original design

• The paintComponent() method contains the code for calculating and displaying a parabola

• The code for this method is shown next

Page 58: Design Patterns in Java Chapter 4 Façade

58

• protected void paintComponent(Graphics g)• {• super.paintComponent(g); // paint the background• int nPoint = 101;• double w = getWidth() - 1;• double h = getHeight() - 1;• int[] x = new int[nPoint];• int[] y = new int[nPoint];• for (int i = 0; i < nPoint; i++) {• // t goes 0 to 1• double t = ((double) i) / (nPoint - 1);• // x goes 0 to w• x[i] = (int) (t * w);• // y is h at t = 0 and t = 1, and y is 0 at t = .5• y[i] = (int) (4 * h * (t - .5) * (t - .5));• }• g.drawPolyline(x, y, nPoint);• }

Page 59: Design Patterns in Java Chapter 4 Façade

59

• The book states that there is no need for a class constructor

• There are static utility methods to wrap a title around the panel and define a standard font

• The code for these methods is shown next

Page 60: Design Patterns in Java Chapter 4 Façade

60

• public static TitledBorder createTitledBorder(String title)• {• TitledBorder tb =

BorderFactory.createTitledBorder(BorderFactory .createBevelBorder(BevelBorder.RAISED), title, TitledBorder.LEFT, TitledBorder.TOP);

• tb.setTitleColor(Color.black);• tb.setTitleFont(getStandardFont());• return tb;• }

Page 61: Design Patterns in Java Chapter 4 Façade

61

• public static JPanel createTitledPanel(String title, JPanel in)• {• JPanel out = new JPanel();• out.add(in);• out.setBorder(createTitledBorder(title));• return out;• }

• public static Font getStandardFont()• {• return new Font("Dialog", Font.PLAIN, 18);• }

Page 62: Design Patterns in Java Chapter 4 Façade

62

• The createTitledPanel() method tucks the provided control inside a bevel border to provide a little padding

• This keeps the displayed flight path parabola from touching the sides of the panel

• The main() method also adds padding to the form object that it uses to contain the applications controls

• The code for the main() method is given next

Page 63: Design Patterns in Java Chapter 4 Façade

63

• public static void main(String[] args)• {• ShowFlight fp = new ShowFlight();• fp.setPreferredSize(new Dimension(300, 200));• JPanel fp_titled = createTitledPanel("Flight Path",

fp);

• JFrame frame = new JFrame("Flight Path for Shell Duds");

• frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);• frame.getContentPane().add(fp_titled);

• frame.pack();• frame.setVisible(true);• }

Page 64: Design Patterns in Java Chapter 4 Façade

64

• The following picture was shown earlier when discussing the goals of parameterization

• This is the output of the program given

Page 65: Design Patterns in Java Chapter 4 Façade

65

Page 66: Design Patterns in Java Chapter 4 Façade

66

• The code of the ShowFlight class manifestly works

• It can be improved and made more reusable by separating it into classes with distinct purposes

• A design review might lead to the following proposed changes

Page 67: Design Patterns in Java Chapter 4 Façade

67

• Introduce a Function class with a method f() that accepts a double (the value of time) and returns a double (the function’s value)

• Write subclasses of the Function class which contain the code for parametric equations

• Move the plotting code of ShowFlight into a PlotPanel class• Let the PlotPanel class do plotting by receiving objects of

the Function class, which generate the needed x and y values

• Move the createTitledPanel() method into a UI utility class

Page 68: Design Patterns in Java Chapter 4 Façade

68

• Following is an incomplete UML diagram which outlines the changes listed above

• In summary, it shows a refactoring of the design of ShowFlight into a set of classes that each has one job

Page 69: Design Patterns in Java Chapter 4 Façade

69

Page 70: Design Patterns in Java Chapter 4 Façade

70

• Challenge 4.4• Complete the diagram in Figure 4.5 to show

the code for ShowFlight refactored into three types: a Function class, a PlotPanel class that plots two parametric functions, and a UI façade class. In your redesign, make the ShowFlight2 class create a Function for y values, and have a main() method that launches the application.

Page 71: Design Patterns in Java Chapter 4 Façade

71

Solution 4.4

Page 72: Design Patterns in Java Chapter 4 Façade

72

• Note something about the given solution diagram:

• There are not connectors between all of the classes represented

• On the one hand, there is no law that says that everything has to be interconnected

• On the other hand, it is a sign that the conclusion of the chapter is somewhat fragmented

Page 73: Design Patterns in Java Chapter 4 Façade

73

• The first thing to consider in the UML solution diagram is the class name UI

• This is the class where the tools for using the graphical elements of Java are kept

• In particular, this is where the createTitledPanel() method is put

• It is the façade class in the new design

Page 74: Design Patterns in Java Chapter 4 Façade

74

• The rest of the chapter consists of the solution code and explanations of it

• As mentioned earlier, the authors’ presentation is somewhat fragmented

• The overheads attempt to fill in some blanks along the way

• The authors’ coding style is also different from my coding style, for example

• The overheads also attempt explain some of what’s going on with the code

Page 75: Design Patterns in Java Chapter 4 Façade

75

The End?

• The rest of the chapter continues to elaborate on how the example illustrates the façade design pattern

• In a sense, equally importantly, it illustrates how application specific functionality and features can be abstracted out into separate classes

• If there is time, these topics will be pursued further in class

• Otherwise, it will be up to students to read the sections in the book and the remainder of these overheads on their own

Page 76: Design Patterns in Java Chapter 4 Façade

76

• Along with the UML solution diagram at the back of the book, the authors also give code for this class

• The code is partial, because they only show that part which is related to the current example

• They really do use this as a façade/toolkit for the rest of the Oozinoz code, and the full implementation of the class has lots of methods in it

• The code for this follows

Page 77: Design Patterns in Java Chapter 4 Façade

77

• public class UI• {• public static final UI NORMAL = new UI();

• protected Font font = new Font(“Book Antiqua”, Font.PLAIN, 18);

• // lots omitted

• public Font getFont()• {• return font;• }

Page 78: Design Patterns in Java Chapter 4 Façade

78

• public TitledBorder createTitledBorder(String title)• {• TitledBorder border =

BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED), title, TitledBorder.LEFT, TitledBorder.TOP);

• border.setTitleColor(Color.black);• border.setTitleFont(getFont());• return border;• }

Page 79: Design Patterns in Java Chapter 4 Façade

79

• public JPanel createTitledPanel(String title, JPanel in)• {• JPanel out = new JPanel();• out.add(in);• out.setBorder(createTitledBorder(title));• return out;• }

Page 80: Design Patterns in Java Chapter 4 Façade

80

• If nothing else, the foregoing code shows the shortcomings of trying to illustrate a particular concept using an integrated example

• In particular, the book indicates that in order to understand fully, it’s necessary to take a look at chapter 8 on the Singleton design pattern, and chapter 17 on the Abstract Factory design pattern

Page 81: Design Patterns in Java Chapter 4 Façade

81

• In the meantime, simply note that the book suggests that you might make the methods static

• In this code, the methods are not abstract, which opens up the possibility of extending the UI class

• That would make it possible to design specialized user interfaces by extending the class and overriding the methods

• The alternative would be to make the methods static and have one fixed UI class of tools for making (one kind of) user interface

Page 82: Design Patterns in Java Chapter 4 Façade

82

• Also note that the UI class has a public, static, final instance variable, NORMAL, which is itself an instance of the UI class

• In a way, this is a way around the fact that the methods aren’t static

• If you want to easily use the methods and get the normal user interface, it is not necessary to construct an instance of the UI class

Page 83: Design Patterns in Java Chapter 4 Façade

83

• Notice that a constructor for the UI class isn’t even shown

• Instead of constructing an instance, in your code which uses this façade class, simply refer to UI.NORMAL and call the non-static methods on that static, constant instance of the class

• This use of UI.NORMAL will appear later on in the rest of the refactored code

Page 84: Design Patterns in Java Chapter 4 Façade

84

• Now it’s time to consider the rest of the classes and code in the refactoring of the example

• The Function class is just an abstract class that defines the form that a function method should take

• As an abstract class, it has to have subclasses which actually implement a function method

• The code for this follows

Page 85: Design Patterns in Java Chapter 4 Façade

85

• public abstract class Function• {• public abstract double f(double t);• }

Page 86: Design Patterns in Java Chapter 4 Façade

86

• Continuing with the refactoring, there is now a PlotPanel class

• The PlotPanel class has a single purpose• That is to display a pair of parametric

equations

Page 87: Design Patterns in Java Chapter 4 Façade

87

• The PlotPanel class has an integer instance variable, points, which tells how many points there will be in the plot

• It has two instance variables that are arrays of integers, the sets of values for x and y

• It also has two instance variables which are typed as instances of the abstract Function class

• One instance is an instance of a subclass of Function which implements a parametric f(t) for x

• The other is an instance of a subclass of Function which implements a parametric equation f(t) for y

• The code for this follows

Page 88: Design Patterns in Java Chapter 4 Façade

88

• public class PlotPanel extends Jpanel• {• private int points;• private int[] xPoints;• private int[] yPoints;• private Function xFunction;• private Function yFunction;

Page 89: Design Patterns in Java Chapter 4 Façade

89

• The constructor for the PlotPanel class takes in three parameters:– The number of points– A reference to an object of type Function for x– A reference to an object of type Function for y

• It sets the instance variables using these input parameters

• The code for this follows

Page 90: Design Patterns in Java Chapter 4 Façade

90

• public PlotPanel(int nPoint, Function xFunc, Function yFunc)• {• points = nPoint;• xPoints = new int[points];• yPoints = new int[points];• xFunction = xFunc;• yFunction = yFunc;• setBackground(Color.WHITE);• }

Page 91: Design Patterns in Java Chapter 4 Façade

91

• PlotPanel extends JPanel, and the heart of the class is its paintComponent() method

• In the implementation the values for w and h are obtained by calling the methods getWidth() and getHeight() (and subtracting 1 from the return values)

• In other words, the values used for w and h depend on whatever the current dimensions of the panel are on the screen, and subtracting 1 keeps the graph from touching the edges

Page 92: Design Patterns in Java Chapter 4 Façade

92

• The heart of the paintComponent() is a for loop• Iterating over the number of points in the plot, a current

value for t is computed by dividing the current point number by the total number of points

• The the function f(t) is called on the respective objects xFunction and yFunction

• The results are stored in the arrays for the x and y values• When all values are calculated, they are displayed using

a call to drawPolyline()• The code for this follows

Page 93: Design Patterns in Java Chapter 4 Façade

93

• protected void paintComponent(Graphics graphics)• {• double w = getWidth() – 1;• double h = getHeight() – 1;• for(int i = 0; i < points; i++)• {• double t = ((double i) / (points – 1);• xPoints[i] = (int) (xFunction.f(t) * w);• yPoints[i] = (int) (h * (1 – yFunction.f(t)));• }• graphics.drawPolyline(xPoints, yPoints, points);• }

Page 94: Design Patterns in Java Chapter 4 Façade

94

• Note that paintComponent() is declared protected• Recall that paintComponent() is called as part of a callback

sequence• It is not called directly in application code• This is what makes it mysterious why you might want to

change its access modifier in your implementation• The authors must have their reasons, although it seems

unnecessary to me• It is conceivable that their only reason, like in other places in

their code, is that this is an artifact resulting from having learned how to write C++ before Java

Page 95: Design Patterns in Java Chapter 4 Façade

95

• Before showing other classes in the refactoring, it’s necessary to try and put PlotPanel into the context

• The UI class given earlier was the façade class for this example

• However, the authors also start bringing up the issue of putting classes into packages

Page 96: Design Patterns in Java Chapter 4 Façade

96

• The PlotPanel class is not specific to the problem of displaying a parabola

• It has been written so that it can plot any pair of parametric equations that conform to the requirements of the Function class

• In other words, the PlotPanel class itself has become something of a generic tool for the creation of things in a graphical user interface

Page 97: Design Patterns in Java Chapter 4 Façade

97

• As a result, the authors suggest putting the classes UI and PlotPanel together in a package named com.oozinoz.ui

• Although not mentioned earlier, they suggested putting the Function class into a package of its own, com.oozinoz.function

• All that remains to be shown of the refactoring is the ShowFlight2 class, which is an application which makes use of these other classes in order to specifically display a parabola

Page 98: Design Patterns in Java Chapter 4 Façade

98

• On the one hand, refactoring is supposed to result in simpler, cleaner code

• Also, the kernel idea behind the Façade design pattern is that it makes it easier to use tools packaged up together, sparing the programmer the full complexity of the toolkit

• However, the reality is that the ShowFlight2 code is cryptic unless you have a good grip on the contents of the Façade class

• It is also cryptic unless you have a good grip on how the code was made more general by the introduction of the Function class

Page 99: Design Patterns in Java Chapter 4 Façade

99

• The code for ShowFlight2 is given below• Screen by screen it’s broken into these parts• Imports• The main() method• A private (inner) YFunction class that extends

the Function class so that its f(t) method returns y values for the parameterized version of the parabola equation

Page 100: Design Patterns in Java Chapter 4 Façade

100

• import java.awt.Dimension;• import javax.swing.JFrame;• import com.oozinoz.function.Function;• import com.oozinoz.function.T;• import com.oozinoz.ui.PlotPanel;• import com.oozinoz.ui.UI;

Page 101: Design Patterns in Java Chapter 4 Façade

101

• public class ShowFlight2 {• public static void main(String[] args)• {• PlotPanel p = new PlotPanel(101, new T(), new

ShowFlight2().new YFunction());• p.setPreferredSize(new Dimension(300, 200));

• JFrame frame = new JFrame("Flight Path for Shell Duds");• frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);•

frame.getContentPane().add(UI.NORMAL.createTitledPanel("Flight Path", p));

• frame.pack();• frame.setVisible(true);• }

Page 102: Design Patterns in Java Chapter 4 Façade

102

• private class YFunction extends Function• {• public YFunction()• {• super(new Function[] {});• }

• public double f(double t)• {• // y is 0 at t = 0, 1; y is 1 at t = .5• return 4 * t * (1 - t);• }• }• }

Page 103: Design Patterns in Java Chapter 4 Façade

103

• Final notes on this fragmented presentation• You will notice that there is no inner class

XFunction• However, an x function has to be passed to

the constructor of PlotPanel• If you look in the code, an object new T() is

passed in that position

Page 104: Design Patterns in Java Chapter 4 Façade

104

• Code for the class T is not given• However, it’s not hard to figure out what it would

be like• The idea is that in effect, x = t• If you look back at the paintComponent() method

of the PlotPanel class, that’s where everything is proportioned to w and h

• T.f(t) simply has to be the identity function in order for x to be plotted correctly

Page 105: Design Patterns in Java Chapter 4 Façade

105

Grand Conclusion(?)

• Is the resulting code simpler?• Is the resulting code easier to understand?• Does the example really do a good job of

illustrating the façade design pattern?• Is the resulting code more general and

flexible?• Was it worth the effort?

Page 106: Design Patterns in Java Chapter 4 Façade

106

The End