71
Unit 4 Prototype Summary prepared by Kirk Scott 1

Unit 4 Prototype

  • Upload
    gilead

  • View
    40

  • Download
    0

Embed Size (px)

DESCRIPTION

Unit 4 Prototype. Summary prepared by Kirk Scott. Design Patterns in Java Chapter 18 Prototype. Summary prepared by Kirk Scott. The Introduction Before the Introduction. The idea behind the prototype design pattern itself is not too complex - PowerPoint PPT Presentation

Citation preview

Page 1: Unit 4 Prototype

1

Unit 4Prototype

Summary prepared by Kirk Scott

Page 2: Unit 4 Prototype

2

Design Patterns in JavaChapter 18Prototype

Summary prepared by Kirk Scott

Page 3: Unit 4 Prototype

3

The Introduction Before the Introduction

• The idea behind the prototype design pattern itself is not too complex

• In addition to the pattern itself, the chapter contains an attempt to illustrate it and some general information

• Unfortunately, both the example and the general information have questionable aspects

Page 4: Unit 4 Prototype

4

• As a consequence, this set of overheads will be short

• The basic idea behind prototyping will be explained

• The, instead of trying to cover the chapter in detail, the high points and low points will be covered

• This really just amounts to a critical guide to trying read what’s in the chapter and determine whether it has any value

Page 5: Unit 4 Prototype

5

The Bottom Line

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

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

Page 6: Unit 4 Prototype

6

• You have a range of options:• 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 7: Unit 4 Prototype

7

• As you will see, the book suggests making “copy()” methods.

• This is the only really new thing introduced.• Copy methods may be a useful adjunct to

cloning.• The idea would be that you make a “partial

clone”

Page 8: Unit 4 Prototype

8

• 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

• Any benefit of implementing copying in a separate method may be outweighed by the fact that the code becomes opaque.

• Does the user know what a copy() method does when it’s called and how it differs from a real clone() method?

Page 9: Unit 4 Prototype

9

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.

• Comment mode on:• As stated earlier, if you understand cloning, then

you already understand the most important ideas concerning prototyping

Page 10: Unit 4 Prototype

10

• The book tries to develop a concrete example that illustrates the use of prototyping

• 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

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

Page 11: Unit 4 Prototype

11

Page 12: Unit 4 Prototype

12

• The book uses the term “abstract factory” to describe this design

• The abstract factory pattern will be introduced later

• Understanding it in detail now is unimportant, because the book wants to propose a design which uses prototyping instead

• It is that design that is of interest in this chapter

Page 13: Unit 4 Prototype

13

• In short, the UML diagram shows 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

Page 14: Unit 4 Prototype

14

• 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 15: Unit 4 Prototype

15

• Challenge 18.1• A Prototype design will cut down on the

number of classes that Oozinoz uses to maintain multiple GUI kits.

• Name two other pros or cons of this design approach.

Page 16: Unit 4 Prototype

16

• Comment mode on:• Clearly the statement made in the challenge is

true.• The idea is that the logic for generating the

needed objects will be implemented in the UIKit class rather than in three separate subclasses.

• The book is trying to find a justification for developing a design which uses prototyping, rather than the original design with subclasses.

Page 17: Unit 4 Prototype

17

• Comment mode on regarding the book’s solution:

• Keep in mind that we don’t have to think in terms of “factories”, whatever they may signify in a factory design pattern.

• Every time the term “factory” appears in the solution, simply read “object”

Page 18: Unit 4 Prototype

18

• Solution 18.1• Advantages of this design include the

following.• We can create new factories without creating

a new class; • we could even create a new GUI kit at

runtime.

Page 19: Unit 4 Prototype

19

• We can produce a new factory by copying one and making slight adjustments.

• For example, we can make the GUI kit for a beta release identical to the normal kit except for font differences.

• The Prototype approach lets a new factory’s buttons and other controls “inherit” values, such as colors, from a predecessor factory.

Page 20: Unit 4 Prototype

20

• Disadvantages include the following:• The Prototype approach lets us change values,

such as colors and fonts, for each factory but does not allow us to produce new kits that have different behavior.

• The motivation for stopping the proliferation of UI kit classes is not clear;

• Why is this proliferation a problem?

Page 21: Unit 4 Prototype

21

• We have to put the kit-initialization software somewhere, presumably on static methods on the proposed UIKit class.

• This approach doesn’t really cut down on the amount of code we have to manage.

• For the sake of completeness, the rest of the book’s answer is given on the next overhead, but I don’t propose to read it.

Page 22: Unit 4 Prototype

22

• What’s the right answer? In a situation like this, it may help to experiment: Write code that follows both designs, and evaluate how the design looks in practice. There will be times, though, when team members fundamentally disagree about which direction to take. This is a good thing: It shows that you are surfacing issues and discussing design. If you never disagree, you are probably not hammering out the best design. (For those times when you do disagree, even after thoughtful discussion, you might use an architect, a lead designer, or a neutral third party to break ties.)

Page 23: Unit 4 Prototype

23

• The previous discussion was pretty much a sideshow

• The authors discussed comparative design issues without really spelling out how prototyping would be accomplished

• We don’t really care which design is better• The real question is, what is the prototype

design like?

Page 24: Unit 4 Prototype

24

• Buried in the pros and cons was a partial answer:• It is apparent under prototyping that one object

may be a partial copy of another—where some things are the same, but some are different

• On the other hand, once you see some of the authors’ ideas on prototyping, you may be unsure whether the approach is a good idea anyway…

Page 25: Unit 4 Prototype

25

• Continuing with the book’s presentation, the next paragraph is not very satisfying

• The book talks about making objects by copying other objects

• You then find this sentence:• “However, the Prototype approach in Java

does not allow new objects to have methods different from those of their parent.”

Page 26: Unit 4 Prototype

26

• Again, the authors are implicitly trying to compare a design with subclasses with a design that uses prototyping

• A subclass might have an entirely different method

• A copy of an object is restricted to whatever methods there are in the class of the objects being copied

Page 27: Unit 4 Prototype

27

Prototyping with Clones

• This section of the chapter basically boils down to a (lame) review of cloning

• I repeat: If you survived CS 202 and remember anything from it, there should no surprises here

• As a matter of fact, you should have a better grasp of things than that given by this section of the book

Page 28: Unit 4 Prototype

28

• Challenge 18.2• The Object class includes a clone() method

that all objects inherit. • If you’re not familiar with this method, look it

up in online help or other documentation. • Then write in your own words what this

method does.

Page 29: Unit 4 Prototype

29

• Solution 18.2• There is no reason to copy the book’s long-

winded answer to this question• The answer is that the clone() method

inherited from the Object class makes shallow copies

Page 30: Unit 4 Prototype

30

• Challenge 18.3• Suppose that the Machine class had two

attributes: • an integer ID and a Location, where Location is a

separate class.• Draw an object diagram that shows a Machine

object, its Location object, and any other objects that result from invoking clone() on the Machine object.

Page 31: Unit 4 Prototype

31

• Solution 18.3• There is no reason to copy the book’s long-

winded answer to this question• The UML diagram showing the result is given

on the next overhead• What the book is trying to describe here is a

shared reference when a shallow copy is made• We know that this isn’t a desirable situation

Page 32: Unit 4 Prototype

32

Page 33: Unit 4 Prototype

33

The Book’s Code for Implementing the Prototype Design Pattern

• This is where the book finally tries to give some code that implements the design pattern

• Depending on your point of view, this is where the book goes completely off the rails

• Instead of just dealing with prototyping by means of careful cloning, they decide to cloak the cloning issues by writing copy() methods which are based on cloning

Page 34: Unit 4 Prototype

34

• At various points in the book it becomes apparent that the authors do what they do because they were originally C++ programmers, not Java programmers

• It’s not clear whether the implementation of cloning in C++ is such that that is also the case in their discussion of prototyping and their desire to implement copy() methods

• In any case, 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 35: Unit 4 Prototype

35

• public class OzPanel extends Jpanel implements Cloneable

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

Page 36: Unit 4 Prototype

36

• I find this example very unsatisfying• It doesn’t even accomplish the goal of doing a

partial copy, the only justification I can see for creating copy() methods rather than using clone() methods

• At the same time, it is both stupid and potentially wrong

Page 37: Unit 4 Prototype

37

• It’s stupid because it is just a sham attempt to make cloning public

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

• It is potentially wrong because it doesn’t include a try/catch block

• The copy() method doesn’t explicitly try to handle the throwing of a CloneNotSupported exception

Page 38: Unit 4 Prototype

38

• The book actually does claim that the 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 39: Unit 4 Prototype

39

• When you make a copy, all inherited instance variables will be initialized to agree with the copy

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

Page 40: Unit 4 Prototype

40

• 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 41: Unit 4 Prototype

41

Page 42: Unit 4 Prototype

42

• Every concrete fact that the book states is true• But if copying in this way (cloning, in effect) is

problematic, this still begs the question, when you make an instance of OzPanel using prototyping, what values would you like the instance variables inherited from JPanel to take on, if not the values of the object that the prototype is being derived from?

Page 43: Unit 4 Prototype

43

• In at least partial answer to this question, the book then proposes the following challenge

Page 44: Unit 4 Prototype

44

• 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 45: Unit 4 Prototype

45

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

Page 46: Unit 4 Prototype

46

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

Page 47: Unit 4 Prototype

47

• 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 48: Unit 4 Prototype

48

• Comment mode on:• Although the book says that this is prototyping

in spirit, it doesn’t really make a copy of something

• When discussing cloning in CS 202, one of the valid (and possibly most desirable) options is just to forget about cloning and make objects from scratch

Page 49: Unit 4 Prototype

49

• I still find semantic fault with the authors’ claims• You can’t avoid inherited instance variables,

whatever superclass they may come from• It’s just a question of what values they take on• This code simply implements a particular

decision about default initialization for some of the instance variables and explicit initialize others to the desired values

Page 50: Unit 4 Prototype

50

• Therefore, the method given is not really a copy() method

• It is a partial copy() method• This apparently what prototyping boils down to• The goal is to be able to make a new object based on

an existing object, but not necessarily be committed to making a full clone—selectively copying some of the original object’s instance variable values and relying on default construction values for the rest

Page 51: Unit 4 Prototype

51

Another Example

• You may recall the following from the development of the Wari examples in CS 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 52: Unit 4 Prototype

52

• 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 53: Unit 4 Prototype

53

• 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 54: Unit 4 Prototype

54

• 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 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 55: Unit 4 Prototype

55

• 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 complete code for the the CupV21 class is given on the following overheads

Page 56: Unit 4 Prototype

56

• This code has been modified• It 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 simply for reference

purposes

Page 57: Unit 4 Prototype

57

• 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;• }

Page 58: Unit 4 Prototype

58

• 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 59: Unit 4 Prototype

59

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

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

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

Page 60: Unit 4 Prototype

60

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

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

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

Page 61: Unit 4 Prototype

61

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

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

Page 62: Unit 4 Prototype

62

Comments on the Example

• Notice that in this example, in contrast to the book examples, 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 63: Unit 4 Prototype

63

• When considering the code, you 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 64: Unit 4 Prototype

64

• 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 is makes little sense to do so

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

Page 65: Unit 4 Prototype

65

UML for the Pattern• The singleton pattern is so simple that there is no

particular UML diagram that illustrates it• You would most likely 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

• 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 contains a comment that makes it clear that the method in question implements prototyping

Page 66: Unit 4 Prototype

66

Summary

• The book’s summary continues the pattern of the rest of the chapter

• Most of it is an unremarkable review of things already stated or claimed

• On the other hand, it also includes statements like those given on the next overhead

Page 67: Unit 4 Prototype

67

• “A major difference between calling a constructor and copying an object is that a copy typically includes some of the state of the original object. You can use this to your advantage, particularly when different “classes” of objects differ only in their attributes and not in their behaviors. In such a case, you can create new classes at runtime by crafting prototypical objects for a client to copy.”

Page 68: Unit 4 Prototype

68

• The preceding statement is not necessarily perfectly clear.

• The operative phrase is “a copy typically includes some of the state of the original object”.

• In other words, it doesn’t contain all of the state of the original object.

• In other words, it’s only a partial copy.

Page 69: Unit 4 Prototype

69

• Finally, there is one last statement in the book’s summary that is potentially unfelicitous:

• “…you can create new classes at runtime by crafting prototypical objects for a client to copy.”

• This isn’t literally true.• You don’t create new classes.

Page 70: Unit 4 Prototype

70

• The book seems to be appealing back to the original UIKit/subclass (factory) example in this statement.

• What they mean to say is that by creating new objects based on prototyping you can mimick a design that has multiple subclasses.

• However, what you create are literally new objects, not classes.

Page 71: Unit 4 Prototype

71

The End