Chapter 18 Prototype

63
Chapter 18 Prototype Summary prepared by Kirk Scott 1

description

Chapter 18 Prototype. Summary prepared by Kirk Scott. Design Patterns in Java Chapter 18 Prototype. Summary prepared by Kirk Scott. Ivory-billed Woodpecker From Wikipedia, the free encyclopedia Jump to: navigation , search Not to be confused with Ivory-billed Woodcreeper . - PowerPoint PPT Presentation

Transcript of Chapter 18 Prototype

Page 1: Chapter  18 Prototype

1

Chapter 18Prototype

Summary prepared by Kirk Scott

Page 2: Chapter  18 Prototype

2

Design Patterns in JavaChapter 18Prototype

Summary prepared by Kirk Scott

Page 3: Chapter  18 Prototype

3

• Ivory-billed Woodpecker• From Wikipedia, the free encyclopedia• Jump to: navigation, search • Not to be confused with Ivory-billed

Woodcreeper.

Page 4: Chapter  18 Prototype

4

• The Ivory-billed Woodpecker (Campephilus principalis) is one of the largest woodpeckers in the world, at roughly 20 inches in length and 30 inches in wingspan. It was native to the virgin forests of the southeastern United States (along with a separate subspecies native to Cuba). Due to habitat destruction, and to a lesser extent hunting, its numbers have dwindled to the point where it is uncertain whether any remain. Almost no forests today can maintain any Ivory-billed Woodpecker population.

Page 5: Chapter  18 Prototype

5

Page 6: Chapter  18 Prototype

6

• The name Campephilus means "lover of grubs" - an allusion to the diet of these birds, many of which feed on the larvae of wood-boring beetles. Contrary to long-held opinion, their closest relatives are not the large black Dryocopus woodpeckers: instead, they are related to the Chrysocolaptes flamebacks from Southeast Asia (Benz et al., 2006).

Page 7: Chapter  18 Prototype

7

Zygodactyly

• Zygodactyly (from Greek ζυγον, a yoke) is an arrangement of digits in birds and chameleons, with two toes facing forward (digits 2 and 3) and two back (digits 1 and 4). This arrangement is most common in arboreal species, particularly those that climb tree trunks or clamber through foliage. Zygodactyly occurs in the parrots, woodpeckers (including flickers), cuckoos (including roadrunners), and some owls. Zygodactyl tracks have been found dating to 120-110 Ma (early Cretaceous), 50 million years before the first identified zygodactyl fossils.[2]

Page 8: Chapter  18 Prototype

8

Illustration of left foot, showing Zygodactyly typical of woodpeckers.

Page 9: Chapter  18 Prototype

9

The Introduction Before the Introduction

• The goal of prototyping is to construct a new object based on an existing object

• The bottom line is that if you remember the discussion of cloning from CSCE 202, you know the most important things there are to know about prototyping

Page 10: Chapter  18 Prototype

10

• The range of options for copying/cloning includes:

• Make a new object from scratch and initialize it to the values of an existing object

• Make a shallow copy, assuming a shallow copy is acceptable

• Make a deep copy• Either of the last two options may be done using

a clone() method in Java

Page 11: Chapter  18 Prototype

11

• The book suggests making “copy()” methods.• The new idea that comes with prototyping is

making partial copy() methods• In other words, you make a copy of a given

object, but some of the instance variables are initialized to default values, while others are initialized to the values in the object being copied

Page 12: Chapter  18 Prototype

12

Side Note on Terminology

• If you talk about partial copies, it would be possible to slip into talking about a “partial clone”

• I just wanted to suggest that “partial clone” is a contradiction in terms, and I would avoid that terminology

Page 13: Chapter  18 Prototype

13

Prototyping vs. Copying vs. Cloning

• There is also a potential pitfall even when being careful to speak in terms of copy() methods rather than clone() methods

• Copying may be a convenient way to bring useful instances of objects into existence, but the client needs to be aware of the distinction between copying and cloning

• If the fact that something is a partial copy is important, it needs to be clear

Page 14: Chapter  18 Prototype

14

Book Definition of the Prototype Design Pattern

• Book definition:• The intent of the Prototype pattern is to

provide new objects by copying an example rather than by bringing forth new, uninitialized instances of a class.

Page 15: Chapter  18 Prototype

15

• The book develops a concrete example that illustrates the use of prototyping

• This is the first example we’ll see that exhibits these these characteristics:

• It is based on Oozinoz• It is part of a larger, relatively complete, object-

oriented, graphical code base• The example is based on showing one solution

and then refactoring it by applying a pattern

Page 16: Chapter  18 Prototype

16

• Rather than being given a toy example, we have to accept the premises of a complex system

• We have to understand the shortcomings of a given design

• We have to see how a subset of that system can be refactored with the design pattern

Page 17: Chapter  18 Prototype

17

• The example involves alternative designs for a system that is supposed to support multiple graphical user interfaces

• The graphical user interfaces are supported by an underlying user interface kit, a UIKit class, which contains methods which create elements of the UI

Page 18: Chapter  18 Prototype

18

• This is an outline of the initial design:• There is a UIKit superclass• There are three subclasses, HandheldUI,

WideScreenUI, and BetaUI• Each of the subclasses supports a separate look

and feel for the application in different environments

• The UML diagram shown on the next overhead illustrates this design approach

Page 19: Chapter  18 Prototype

19

Page 20: Chapter  18 Prototype

20

An Alternative Design

• The book uses this as the starting point for an example where you might use prototyping

• Instead of having three subclasses to the UIKit class, this alternative is proposed:

• The UIKit class should contain static methods which can be called in order to generate the UI objects needed for various different UI environments

Page 21: Chapter  18 Prototype

21

The Book’s Code for Implementing the Prototype Design Pattern

• This is where the book gives initial example code that is supposed to implement the design pattern

• Instead of dealing with prototyping by means of careful cloning, they implement prototyping by writing a copy() method which is based on cloning

Page 22: Chapter  18 Prototype

22

• The example they give is of a method that makes it possible to “copy” a panel, a GUI component that might appear in a UIKit

• The code is given on the next overhead

Page 23: Chapter  18 Prototype

23

• public class OzPanel extends Jpanel implements Cloneable

• {• public OzPanel copy()• {• return (OzPanel) this.clone();• }• }

Page 24: Chapter  18 Prototype

24

Apparent Problems with the Book’s Example

• The thing to understand is that the book is trying to go step-by-step

• It starts with a scenario and proposes a solution

• But the solution is not complete and correct• They’re trying to model the process of code

development

Page 25: Chapter  18 Prototype

25

• As part of their approach, the book kind of beats around the bush

• I would like to lead by just pointing out some of the obvious flaws with what they’ve done so far

• As given, the method doesn’t even accomplish the goal of doing a partial copy, the basic reason for creating copy() methods rather than using clone() methods

Page 26: Chapter  18 Prototype

26

• At the same time, it seems to be both unwise and potentially wrong

• It’s unwise because it is effectively just an attempt to make cloning public

• If you’re going to clone, there is a way to make cloning public using the tools of Java

Page 27: Chapter  18 Prototype

27

• It’s potentially wrong because it still doesn’t deal with the issue that the inherited clone() method makes shallow copies

• We don’t know at this point whether deep or shallow copies are needed

Page 28: Chapter  18 Prototype

28

• The copy() method also doesn’t include a try/catch block for the call to clone()

• It doesn’t explicitly try to handle the throwing of a CloneNotSupported exception—which may result depending on how the clone() method was implemented

Page 29: Chapter  18 Prototype

29

• Sometimes anomalies in the book can be explained by the fact that the authors started as C++ programmers

• In this example, I don’t know enough about C++ to say whether that’s the case

• If by chance you are a C++ programmer and you are comfortable with the way this code was written, my goal is to make you uncomfortable…

Page 30: Chapter  18 Prototype

30

The Book’s Critique of its own Example

• The book actually does claim that their code is dangerous

• This is allegedly due to its inheritance characteristics

• The authors point out the obvious fact that OzPanel, as a subclass of JPanel, will inherit attributes from it and all of its superclasses

Page 31: Chapter  18 Prototype

31

• Their point is that if you aren’t familiar with all of the superclasses, can you be satisfied with all of the default values that come from them?

• The reality is, that as a dyed-in-the-wool object-oriented programmer, I am accustomed to accepting default initialization of inherited instance variables for a long time

• Should I be worried?

Page 32: Chapter  18 Prototype

32

What’s the Real Point of the Book’s Example?

• The book points out that for GUI purposes, the most important instance variables may actually be in a higher superclass, Component, not in JPanel

• These attributes include things like the foreground, the background, and the font, for example

• They illustrate that fact with the UML diagram on the following overhead

Page 33: Chapter  18 Prototype

33

Page 34: Chapter  18 Prototype

34

• What the book is driving at is that they’re trying to motivate the idea that you probably really want only a partial copy

• In other words, they are conceding that a copy() method that is just a cloaked clone() method doesn’t really serve the purpose of prototyping

• The book pursues this idea in the following challenge

Page 35: Chapter  18 Prototype

35

• Challenge 18.4• Write an OzPanel.copy2() method that copies

a panel without relying on clone(). • Assume that the only attributes that are

important to a copy are background, font, and foreground.

Page 36: Chapter  18 Prototype

36

• Solution 18.4• “A reasonable solution is as follows:• [Code is given on the next overhead.]

Page 37: Chapter  18 Prototype

37

• public OzPanel copy2()• {• OzPanel result = new OzPanel();• result.setBackground(this.getBackground());• result.setForeground(this.getForeground());• result.setFont(this.getFont());• return result;• }

Page 38: Chapter  18 Prototype

38

• Solution 18.4, continued:• Both the copy() method and the copy2() method

relieve clients of OzPanel from invoking a constructor and thus support the Prototype idea.

• However, the manual approach of copy2() may be much safer.

• This approach relies on knowing which attributes are important to copy, but it avoids copying attributes that you may know nothing about.”

Page 39: Chapter  18 Prototype

39

• Comment mode on:• To state the obvious, in this second example, the

prototyping code does call a constructor rather than calling a clone() method

• But the client code does not call the constructor directly

• It is spared the trouble of extracting desired values to copy and then calling a constructor which accepts those values as paramenters

Page 40: Chapter  18 Prototype

40

• Comment mode continued:• If prototyping is making a partial copy, then

this example implements prototyping• It creates a new object from scratch, with

default values for its instance variables• It then initializes some important instance

variables to the values of the particular object that’s being prototyped

Page 41: Chapter  18 Prototype

41

• Comment mode continued:• The book’s explanation seems a little garbled

to me• It’s not that I’m worried about inherited

instance variables in general, and their default initialization

Page 42: Chapter  18 Prototype

42

• I am perfectly happy, as usual, to accept default initialization for large numbers of inherited instance variables that I know nothing about

• It is precisely those that I do know something about that I choose to initialize to values I also know something about because they are the values in an object which I already have possession of

Page 43: Chapter  18 Prototype

43

• I have a specific purpose in mind• If I’m thinking clearly, then it’s a simple matter

to make sure I copy over the values that I really want

• In this example, concretely, that makes sure there’s consistency between the different graphical user interfaces

Page 44: Chapter  18 Prototype

44

Another Example

• You may recall the following from the development of the Wari examples in CSCE 202:

• There was a version of the code where there was just one Cup class

• That class had instance variables for an owner, a link to the next cup, and a count of the number of seeds

• That cup class was suitable for the playable cups on the board

Page 45: Chapter  18 Prototype

45

• By simply ignoring the link to the next cup, that cup class could also serve as a captured cup

• An alternative design had the captured cup as a superclass, lacking a link, and the playable cup as a subclass, containing that additional instance variable

Page 46: Chapter  18 Prototype

46

• It can’t be said that there is any particular advantage to using prototyping in this case, but the foregoing scenario can be adapted to illustrate prototyping.

• You could use the design that only has the one kind of cup, and to create a captured cup for a given player, you could prototype one of that player’s playable cups.

Page 47: Chapter  18 Prototype

47

• The captured cup would be a partial copy of the playable cup

• You would want to copy the value indicating who the cup belonged to

• You would want the seed count to be given the default initial value of 0, because that is how the captured cup should start—regardless of how many seeds might be in the playable cup that is being copied

Page 48: Chapter  18 Prototype

48

• And you would want the link instance variable to take on the default value of null, because the captured cup is never linked to any other cup

• The code for the CupV21 class is given on the overheads following the next one, with modifications

Page 49: Chapter  18 Prototype

49

• The class has had a default constructor added to it

• It has also had a prototyping method added to it

• In order to make it easy to identify the changes, these have been put at the very beginning

• The rest of the code is given for reference purposes

Page 50: Chapter  18 Prototype

50

• public class CupV21• {• private int seedCount;• private int whoseCup;• private CupV21 nextCup;

• public CupV21()• {• seedCount = 0;• whoseCup = 0;• nextCup = null;• }

• public CupV21 partiallyCopyPlayableCupToGiveCapturedCup()• {• CupV21 retCup = new CupV21();• retCup.whoseCup = this.whoseCup;• return retCup;• }

Page 51: Chapter  18 Prototype

51

• public CupV21(int seedCountin, int whoseCupin)• {• seedCount = seedCountin;• whoseCup = whoseCupin;• nextCup = null;• }

• public CupV21(int seedCountin, int whoseCupin, CupV21 nextCupin)

• {• seedCount = seedCountin;• whoseCup = whoseCupin;• nextCup = nextCupin;• }

Page 52: Chapter  18 Prototype

52

• public String toString()• {• return "CupV21[seedCount = " + seedCount• + ", whoseCup = " + whoseCup• + "]";• }

• public int getSeedCount()• {• return seedCount;• }

• public void addOneSeed()• {• seedCount++;• }

Page 53: Chapter  18 Prototype

53

• public void addSomeSeeds(int seedsin)• {• seedCount += seedsin;• }

• public int getWhoseCup()• {• return whoseCup;• }

• public CupV21 getNextCup()• {• return nextCup;• }

Page 54: Chapter  18 Prototype

54

• public void setNextCup(CupV21 nextCupin)• {• nextCup = nextCupin;• }

• public int removeSeeds()• {• int temp = seedCount;• seedCount = 0;• return temp;• }• }

Page 55: Chapter  18 Prototype

55

Comments on the Example

• Notice that in this example cloning is not used• The prototyping method starts by calling the

default constructor to make a brand new object with default values

• It then takes the one instance variable value of the implicit parameter that is of interest and uses it to set the value in the object to be returned

Page 56: Chapter  18 Prototype

56

• When considering the code, you might wonder about this:

• What would happen if you called the prototyping method on a captured cup rather than a playable cup?

• Syntactically it would work, although practically there should be no reason to do this

Page 57: Chapter  18 Prototype

57

• The moral of the story is that in a design that includes this pattern, as always, writers of client code have to know what they’re doing

• The result of a call to prototype is an object of the right type to call the prototyping method on again, but it makes little sense to do so

• You would just go in circles, deriving useless new objects

Page 58: Chapter  18 Prototype

58

UML for the Pattern

• The prototype pattern is so simple that I have devised no particular UML diagram that illustrates it• You would might include it in a UML

diagram of a design, or recognize it in a UML diagram of a design, by means of a method given in the box representing a class

Page 59: Chapter  18 Prototype

59

• The method may have a name, like copy(), or prototype(), that indicates that it implements the pattern

• The diagram may also included a box with a dog-eared corner that shows the code or contains a comment that makes it clear that the method in question implements prototyping

Page 60: Chapter  18 Prototype

60

• Lasater’s UML diagram is given on the next overhead.

• Using that author’s terminology, the pattern is recognizable by the subclass, the operation() method to prototype, and the use of the clone() method in the prototype classes.

Page 61: Chapter  18 Prototype

61

Page 62: Chapter  18 Prototype

62

Summary

• Prototyping means in some sense making new objects by copying existing objects

• It differs from cloning because only partial copies are created

• Some of the instance variable values of the new objects are the default values, while others are copied from the existing object.

• Prototyping is partial copying

Page 63: Chapter  18 Prototype

63

The End