New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Miracle Jaskolski
Miracle Jaskolski
GPA 3.75

Edward Gehringer

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Edward Gehringer
Class Notes
25 ?




Popular in Course


This 79 page Class Notes was uploaded by Miracle Jaskolski on Thursday October 15, 2015. The Class Notes belongs to ECE 517 at North Carolina State University taught by Edward Gehringer in Fall. Since its upload, it has received 92 views. For similar materials see /class/223893/ece-517-north-carolina-state-university in ELECTRICAL AND COMPUTER ENGINEERING at North Carolina State University.

Similar to ECE 517 at NCS



Reviews for Object


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/15/15
Design Patterns Prototype State Composite Memento Let s start by considering the Outline for Lecture 24 CanvasEditor as we had it at the end of the last Class The Prototype pattern The State pattern Recall that when a button was clicked the III The Composite button s custom ActionListener was pattern invoked and it set the current figure to the IV The Memento pattern proper type rectButton addActionListener new ActionListener public void actionPerformed ActionEvent ae canvasEditor setCurrentFigure new Rect0 0 60 40 The setCurrentFigure message was received by the canvasEditor object Let s take a look at the code for it public class CanvasEditor implements MouseListener private Figure currentFigure public CanvasEditor Figure initialFigure this currentFigure initialFigure public void setCurrentFigure Figure newFigure currentFigure newFigure public void mouseClicked MouseEvent e Figure newFigure a new figure based on currentFigure DrawingCanvas e getSource addFigure newFigure Lecture 24 ObjectOriented Languages and Systems 1 public void mousePressedMbuseEvent e public void mouseReleasedMbuseEvent e public void mouseEnteredMbuseEvent e public void mouseExitedMouseEvent e Notice that we haven t said how to draw a new figure based on the current figure Prototype Skrien 85 How shall we draw this figure Can we use the currentFigure object Can we use a constructor to create it Should we test which kind of figure that we need if currentFigure instanceof Ellipse newFigure new Ellipse else if currentFigure instanceof Rect newFigure new Rect else newFigure new Square Of course not Instead we can just conethe current object This makes use of Java s Cloneable interface By implementing Cloneable a class allows fieldbyfield copies to be made of its instances This allows the Figure referred to by currentFigure to act as a prototype for the figure to be created Here is the code public Object clone CSCECE 517 Lecture Notes 2007 Edward F Gehringer try return superclone catch CloneNotSupportedException e This should never happen eprintStackTrace return null Why does the method call super clone What class do we place this definition in How do we use this method to create a new figure based oncurrentFigure public void mouseClickedMbuseEvent e Figure newFigure Figure currentFigureclone newFiguresetCenteregetX egetY DrawingCanvas egetSource addFigurenewFigure This is an instance of the Prototype pattern Lecture 24 ObjectOriented Languages and Systems 3 mpementa azyg39 Each class that is going to create an iject must have a prototypical39object The parent class implements the Gloneable int erfac e Then the creationinitiating object clones itself producing anobject ofthecorrect class State Skrien 86 We ve been talking about bad uses of case statements in programs Another way in which case statements are sometimes used is to implement finitestate machines Here s an example Tabe form of FSM StateInput input1 input2 input3 input4 State l different actions for each State2 combination of state and State3 input while state Final switch state case Statel if input inputlactionll else if input input2 action12 else if input input3 actionl3 else if input input4 actionl4 break case State2 if input inputlaction21 else if input input2 action22 else if input input3 action23 else if input input4 action24 break default Systemoutprintlnquothnmhdsuua39 state How can we do this in a more oo fashion Hint We can make State an interface CSCECE 517 Lecture Notes 2007 Edward F Gehringer 4 public interface How should the states be defined How should these methods be implemented for each state Let s see how this approach could help our drawing program So far our application just creates figures and puts them at different places on the canvas Once positioned they stay in the same place forever We d like to enhance the app to allow the figures to move This requires adding a selection tool to the menu When the selection tool is chosen and Lecture 24 the user clicks the mouse button inside an unselected figure then that figure becomes the only selected figure the user clicks the mouse button inside a selected figure or outside all the figures nothing changes the user presses the mouse inside an unselected figure and drags then that figure becomes the only selected figure and is dragged along with the mouse the user presses the mouse inside a selected figure and drags then that figure and all other currently selected figures are dragged with the mouse the user presses the mouse outside all figures and drags the mouse a selection area is outlined and all figures intersecting the selection area become the selected figures ObjectOriented Languages and Systems This is pretty standard behavior for drawing applications It requires a major change to our application Until now we were able to ignore mouse presses drags and releases However ifthe selection tool is chosen they will have to be tracked and various actions will have to be implemented We could do this with conditionals public void mouseClickedMouseEvent e if currentTool selection drawinggetFigureContaining egetX egetY else Figure newFigure Figure currentFigureclone newFiguresetCenteregetX egetY DrawingCanvas egetSourceaddFigure newFigure But do we want to What can we do instead We can use the State pattern quot Am i dllii l l Wild is a umrttiom r wrap j 39 at mi were V re application Delineaseto39b the din mime to a v rom lime lime CSCECE 517 Lecture Notes 2007 Edward F Gehringer momma dices to print a stings wele Weteht maatcem r machine as gamed algo glassy 39 or Jim in the gigalts clawed t dim cuttmti With the State pattern the object needing different behavior will maintain a reference to another object representing its state instead of having the mouseclicked method in the CanvasEditor there are now multiple mouseclicked methods located in the Tool classes Here s the method in Creation39rool public void mouseClickedMouseEvent e Figure newFigure Figure myFigureclone newFiguremoveToegetX newFiguregetBoundingRectwidth 2 egetY newFiguregetBoundingRectheight 2 DrawingCanvas canvas DrawingCanvas egetSource canvasaddFigurenewFigure canvasunselectAll canvasselectFigurenewFigure Here s the method in Selection39rool Lecture 24 ObjectOriented Languages and Systems 7 public void mouseClickedMouseEvent e DrawingCanvas canvas DrawingCanvas egetSource Figure figure canvasgetFigureContaining egetX egetxm pressedInFigure figure null if pressedInFigure ampamp figureisSelected canvasunselectAll if pressedInFigure figuresetSelectedtrue originx egetX originy egetY Composite Skrien 87 Next we need to allow users to group figures together to make a composite figure which can be manipulated as a single figure Our Drawing class stores all its figures in an ArrayList named figures We could create a separate ArrayList for each group That is to implement the quotGroupquot menu item action we can just 0 remove all the selected figures from figures 0 put those selected figures into a new ArrayList and 0 addthatArrayListtOfigures The problem is that the Drawing class assumes that only Figure objects are in ArrayLists So all drawing methods will have to be rewritten similarly to this if figuresgeti instanceof ArrayList do the desired processing on the group else do the desired processing on the figure Things would get worse if a group contained another group The Composite pattern solves this It has CSCECE 517 Lecture Notes 2007 Edward F Gehringer 8 une ur mure eaf assES representmg mdmduax abject and 3 eumpuete ass representmg cuHemuns uf umeets Bum uf these are subdasses uf a Campanentdass A them can refer m nmpunents Wmut knuvvmg Whetherthey are nmpuswtes ur heave m uur dravvmg program Whmh are the eumpusnes and mm are me Eaves Here x a UML magram Let stake a uuk ata samp e methud drawshape m Each ufthe masses vvmm assw Each m7 public Wm drawshape6raphics an Rel e get tangle rel nundingkect Lecture 2 omeemenee Languages and Svslems gdrawRectrectx recty rectwidth rectheight public void drawShapeGraphics g for IteratorltFiguregt it childreniterator ithasNext itnextdrawShapeg public void drawShapeGraphics g Rectangle rect getBoundingRect gdrawOvalrectx recty rectwidth rectheight 4 39 1 low lii B Emailiwfhalueli it tn 1 compositions orquot A unmi icmmliy came 0 n emit it KeSU I nn 61 quot mli twe Memento A standard feature of an editor is the ability to undo the most recent changes that the user has made Let s add this functionality to our drawing application We39ll do this by adding an undo stack which holds previous states ofthe canvas CSCECE 517 Lecture Notes 2007 Edward F Gehringer 10 The top ofthe stack always corresponds to the current state of the canvas Now what two things should we do when a change is undone We could make the DrawingCanvas handle undoing and redoing But this gives it a lot of extra responsibility Is there a more elegant way The Memento pattern solves this problem It allows an external class to handle the states but doesn t let this external class manipulate them in any way Here is a description of Memento 391 to nits n Ml 3 states n amps Let s take a look at an outline of the code for the undoredo handler More details appear in the book public class UndoRedoHandler private Canvasstatestack undostack redostack private DrawingCanvas canvas Lecture 24 ObjectOriented Languages and Systems 11 public UndoRedoHandlerDrawingCanvas canvas undoStack new CanvasStateStack redoStack new CanvasStateStack thiscanvas canvas Store the initial state of the canvas on the undo stack undoStackpushcanvascreateMemento public void undo if undoStacksize 1 return Only current state is on stack DrawingCanvasState canvasState undoStackpop redoStackpushcanvasState canvasrestoreStateundoStackpeek public void redo if redoStackisEmpty return DrawingCanvasState canvasState redoStackpop undoStackpushcanvasState canvasrestoreStatecanvasState We only need to add two methods to the DrawingCanvas class What are they Here is a UML sequence diagram that shows what happens when a change is undone CSCECE 517 Lecture Notes 2007 Edward F Gehringer 12 menycmwws mengcanwsstme undaMemiitem Adaniaenei UimuRerAuHmmiei regaresmatams The ActionListener for the Undo menu item signals the UndoRedoIIandl at to undo N The UndoRedoIIandler then a extracts the state to be restored 39om its undo stack and b signals the Drawingcanvas to restore its state to that 3 Since the internals ofthe state object are private the Drawingcanvas cannot access them but it can ask the state object to restore the canvas s state for it Lecture 24 ObjEEirOriEnIEd Languages and Systems 13 The Cookbook Application cont To bring up the Cookbook application create a new Ruby project right cick in Package Explorerview then New Project We name the project cookbook and then deselectthe Use default location checkbox New Ruby Project a Pruiect contents directory must be specified I n Evoject name l cankbunk l ll 34 This allows us to use the cookbook code that was downloaded with InstantRaiIs instead of a new copy ofthat code Why is this important We find the downloaded code in CnstantRaisraisappscookbook Lecture 13 ObjectOriented Languages and Systems Select the location divectmy m help a a mini 3 m m ll phpmvadmln a la miss a a Click OK and then Finish Then launch lnstantRails Instant Rails 7 r 7 quot19 ualin a 18 51 Instanl Balk 5mm st n a ing lumu 2318 55 My ql Ennllguiatlon we changed own 231856 Apache Eunllgulalion llle changed Click the little beige I box in the upper righthand comer and choose Rails Applications gt Open Ruby Console Wndow This gives you a terminal window CSCECE 517 Lecture Notes 2007 Edward F Gehrlnger WINDOWSkyslemSka ex an Inuigtcn lnstant ails J lnsta i sgtrn lnstant ailsruhyhinClnstant ailsmysulhin r n flesruhyhin MlNDOMSsystem32CMINDOMS MlNDOMSSystem32MhemC Prn ilesCnmmnn FilesRnxin SharedDLLShare Prng on FilesJauaj2re1 42 Prngram FilesZnne LahsZnne larm ailFrnntier CPrngram FilesQuicin eQISystemClNSI N 1ruhyhinClNSI N 1 pacheC INSI N 1PNP 7m ltmngt ltmngt ltnxngt netoooto ltnxngt cunkhnnk ltn n ypni2 u u bytes 13347uusuu32 bytes free xnstontnoilsxroilseoopsgt Type cd cookbookquot then ruby scriptserverquot This starts the Web server WINDOWSkyslemS cm 2X2 ruhyscr server HE ory nf c xnstontnoilsxroilseooos 12u2 m1 ltmngt ltmngt J ltmngt ltmngt Monk n n ypni2 u u bytes 13347uusuu32 bytes free oxnstontnoilsxroilseooosgtco cunkhnnk InstantRailsrailsapps9nnkhnnkgtruhy seriotseruer nootins nonsrel use 39seriotseruer oehriek39 to force quotEnriekgt 39 39 39 39 o http 3 gt gt gt tdnwn seruer re listening at uu 3uuu s with oe e shu ng loonent enuironnent t so stort ng no so Starting Rail so Rails loooeo so Loooins on Rails Specific cenrlusin y s Signals reody NI stoo nu restort u 3uuu Then we can bring up a Web browser and browse to httpIocalhosmOOO which redirects to httplIocaIhost3000recipeIist Lecture 13 omecronemeu Languages and Systems Online Cookbook Create new recipe Show all recipes Show all categories We can then proceed to exercise the application as we did in the last lecture But now we can change its functionality too Let s make a trivial change Change Show all recipesquot and Show all categoriesquot to List all recipes and List all categoriesquot Where shall we make this change Well if we click on Show all categoriesquot we get this screen Online Cookbook Listing categories Name Snacks Show Edit Diskov Beverages Show L tDEskoy New mequ Create newrecipe Showallrecipzs Show all caterones What do you notice about the bottom line And if we click on Create new recipequot we get this screen CSCECE 517 Lecture Notes 2007 Edward F Gehringer 2 Online Cnnkhnnk ranilla Firelnx Eiie mt wew Higta39v Eamarks Innis deiD gr v i J iu httvHiataihastanonvecivenemii ii 1 i a g Hamming a RsaiPiayer g winaawsmmwam a WW 0 Weathemnmm Online Cookbook cm W range Show 51 ranges Show a enzymes Dane Again the bottom line is the same Let s take a look at the directory listing Which file do you think contains that code Lecture 13 ObjectOriented Languages and Sjstems This is an rhtml file the first time we ve seen this type What do you think it stands for Let s look at the code in this file lthtmlgt ltheadgt ltt1tlegtOnllne Cookbookltt1tlegt ltheadgt ltbod gt lthlgtOnllne Cookbooklthlgt lt content for layout gt ltpgt 7 7 lt llnkito quotCreate new recipequot actlon gt quotnewquot gt lt linkito quotShow all recipesquot controller gt quotrecipequot actlon gt quotllStquot gt CSCECE 517 Lecture Notes 2007 Edward F Gehringer lt linkito quotShow all categoriesquot controller gt quotcategoryquot action gt quotlistquot gt ltpgt ltbodygt lthtmlgt This raises several questions 0 What gets invoked when we click on the Show all recipes link 0 How do we make it say List all recipes 0 What does contentforlayout do 0 What s that strange notation surrounding contentforlayout 0 Where is it specified that a standard layout is used for certain view screens And if we poke around and look at all the views we will find that all have the same navigation bar at the bottom Now to make sure you are following here are some review questions 1 What is the function Of ruby scriptserverquot Lecture 13 ObjectOriented Languages and Systems What URL do we type in to find the homepage of our cookbook application N When we click on Show all categories what URL will be taken to 00 What are the filenames that contain views associated with recipes b What is Embedded Ruby and how have we seen it used 0quot What kind of relationship is there between recipes and categories F 7 Where is this relationship represented The views Now let s take a look at the View code We ll look at it line by line which may obscure the flow but if you have trouble just look in your railsappscookbook directory for the uncommented code ltform actionquot updatelt recipe id gtquot methodquotPOSTquotgt There are three main components here 0 The ltformgt tag 0 The ERB code lt recipe id gt o The POST method ltinput idquotrecipeidquot namequotrecipeidquot sizequot30quot typequothiddenquot valuequotlt recipeid gtquot gt You probably won t figure this out so I ll tell you CSCECE 517 Lecture Notes 2007 Edward F Gehringer o recipeid is a field in the recipes table of the database 0 recipeid is a field of a hash called recipe that will be passed back as POST parameter 0 This is a hidden field because the ID the primary key ofthe recipes table has no reason to appear on the form that edits a recipe However it does need to be passed to the update method so that method knows which row ofthe table to update You should be able to figure out what the ERb code recipeid means but where is that instance variable set ltpgtltbgtTitleltbgtltbrgt ltinput idquotrecipetitlequot namequotrecipetitlequot sizequot30quot typequottextquot valuequotlt recipetitle gtquot gt ltpgt Can you explain this by analogy with the previous ltinputgt tag The next field is very similar ltpgtltbgtDescriptionltbgtltbrgt ltinput idquotrecipedescriptionquot namequotrecipedescriptionquot size 30quot typequottextquot valuequotlt recipedescription gtquot gt ltpgt ltpgtltbgtCategoryltbgtltbrgt Now we use a ltse1ectgt form to put up a list dropbox of categories ltse1ect namequotrecipecategoryidquotgt lt categorieseach do lcategoryl gt ltoption valuequotlt categoryid gtquot lt selected if categoryid recipecategoryid gtgt Lecture 13 ObjectOriented Languages and Systems lt categoryname gt ltoptiongt lt end gt ltselectgtltpgt What does selected do here ltpgtltbgtInstructionsltbgtltbrgt lttextarea cols 40quot idquotrecipeinstructionsquot namequotrecipeinstructionsquot rowsquot20quot wrapquotvirtualquotgt lt recipeinstructions gt lttextareagt ltpgt ltinput typequotsubmitquot valuequotUpdatequot gt ltformgt The rest should be fairly selfexplanatory listrhtml Now that we have seen one view the next one is not very different It begins with some gardenvariety HTML lttable borderquot1quotgt lttrgt lttd widthquot40quotgtltp align centerquotgtltigtltbgtRecipeltbgtltigtlttdgt lttd widthquot20quotgtltp alignquotcenterquotgtltigtltbgtCategoryltbgtltigtlttdgt lttd widthquot20quotgtltp alignquotcenterquotgtltigtltbgtDateltbgtltigtlttdgt lttrgt Then we cycle through each recipe displaying it if that is the appropriate thing to do Where did the recipes instance variable come from How is it deciding whether to display a recipe CSCECE 517 Lecture Notes 2007 Edward F Gehringer 10 lt recipeseach do Irecipel gt lt if category nil II category recipecategorynamegt lttrgt Where does the category variable come from Let s consider each ofthe parameters of the linkto calls below 0 The first link is to a scaffold method which we can consider to be magic for now but if you really want to see it from a command WindOW execute ruby scriptgenerate scaffold ltmodelgt ltcontrollergt where ltmodelgt and ltcontrollergt are both recipe in this case lttdgt lt linkto recipetitle action gt quotshowquot id gt recipeid gt The next link is to the delete method which has a confirm parameter This is a feature of Rails which pops up a dialog box for confirmation before deleting the recipe ltfont sizelgt lt linkto quotdeletequot action gt quotdeletequot id gt recipeid confirm gt quotReally delete recipetitlequot gt ltfontgt lttdgt o The next link displays recipecategoryname and passes two parameters What is the category parameter Lecture 13 ObjectOriented Languages and Systems 11 lttdgt lt linkto recipecategoryname action gt quotlistquot category gt quotrecipecategorynamequot gt lttdgt lttdgtlt recipedate gtlttdgt lttrgt lt end gt lt end gt lttablegt newrhtml The only remaining controller is newrhtm1 It doesn t illustrate much that we haven t seen before so I ll ask you the questions below ltform actionquotrecipecreatequot metho quotpostquotgt ltpgt ltbgtTitleltbgtltbrgt ltinput idquotrecipetitlequot namequotrecipetitlequot sizequot30quot type textquot valuequotquotgt ltpgt ltpgt ltbgtDescriptionltbgtltbrgt ltinput idquotrecipedescriptionquot namequotrecipedescription sizequot30quot typequottextquot valuequotquotgt ltpgt ltpgt ltbgtCategoryltbgtltbrgt ltselect namequotrecipecategoryidquotgt lt categorieseach do lcategoryl gt ltoption valuequotlt categoryid gtquotgt lt categoryname gt ltoptiongt lt end gt ltselectgt ltpgt ltpgt CSCECE 517 Lecture Notes 2007 Edward F Gehringer 12 ltbgtInstructionsltbgtltbrgt lttextarea colsquot40quot idquotrecipeinstructionsquot namequotrecipeinstructionsquot rowsquot20quot wrapquotvirtualquotgt lttextareagt ltpgt ltinput typequotsubmitquot valuequotCreatequotgt ltformgt Which controller is invoked when the form is submitted Where is the code for this controller N Where and in what form is recipe title sent 00 VVhatBthefunc onofthelt categorieseach do lcategoryl gt loop 4 What link or button do we press to submit this form Active Record Our Ruby on Rails programs deal with objects but they are mapped into relational databases There s a mismatch here how are the database tables translated into objects and how are objects created in the program saved to the db Ruby on Rails solution is Active Record In Active Record 0 Database tables correspond to Rails classes 0 Database records rows correspond to Rails objects Lecture 13 ObjectOriented Languages and Systems 13 We can perform operations on tables by invoking class methods as is done in the RecipeController recipes Recipe findall categories Categoryfindall There are also methods that operate on database records These are invoked on objects Can you find some in the code below class RecipeController lt ApplicationController layout quotstandard layoutquot scaffold recipe def new recipe Recipenew categories Categoryfind4all end def list category Params39category39 recipes Recipefind7all end def edit recipe Recipefindparamsquotidquot categories Categoryzfindiall end def create recipe Recipenewparams39recipe39 recipedate Datetoday if recipesave redirect to action gt 39list39 else 7 render action 39new39 end 7 end def delete Recipefindparams39id39destroy redirectito action gt 39list39 end end Notice also that the fields of an object correspond directly to the fields of a database record This means that Ruby code can directly manipulate fields in database records well it can retrieve them via manipulate them and save them back via CSCECE 517 Lecture Notes 2007 Edward F Gehringer 14 Design Patterns Bridge Decorator Chain of Responsibility Interpreter Visitor Bridge Outline for Lecture 26 HFDP 141 Now let s look at the class I Bridge diagram39for the State patternlfor example at Decorator httn wwwexr ltnnr l39lt P Pdll cuhtm Chain of H Note that the Context object holds a Respons39b39l39ty reference to an abstract class This is the 39V Interpreter abstract class from which the concrete states V Visitor are derived It turns out that the same structure is valuable for implementing drivers What39s a driver Drivers are generally used by various applications Consider a printer driver for example There is a driver for a particular printer for each OS Many different applications can use that printer providing that the right driver is present This is an example of the bridge pattern We have various abstractions the applications and various implementations the drivers If the applications aren t in a hierarchy the class diagram for Bridge is exactly the same as the class diagram for State But often the abstractions are in a hierarchy HFDP gives the example of televisions and remotes TVs have behavior in common and so do remotes If they re universal remotesquot they can be used by lots of different kinds of TVs This leads to the UML diagram on p 613 of HFDP orview it online What are the advantages of Bridge OK we just told you the right way to handle this problem What would be the wrong way Can you imagine using a lot more Lecture 26 ObjectOriented Languages and Systems 1 subclasses So one way of looking at Bridge is that it avoids unnecessary subclassing Decorator HFDP Ch 3 Is too much subclassing a good thing Why not HFDP has a good example on p 80 Here a separate subclass is created for each combination of coffee and condiments There are four types of coffee HouseBlend DarkRoast Decaf Espresso There are many condiments eg milk soy mocha whip Each subclass has only one method What is it Attempt 2 Let s use a separate instance variable for each condiment along with setters and getters of course How should we implement cost In the superclass or subclases This is better but still not ideal Why CSCECE 517 Lecture Notes 2007 Edward F Gehringer What principle have we violated How can we solve this problem without using inheritance We will just have the withcondiments versions of our object the original version Look at the diagram on p 89 We start out with a cost for DarkRoast coffee Then if we want the cost of DarkRoast with Mocha we give Mocha a method Mocha39s method calls the a method of Beverage In order to do this Beverage and Mocha should both the same Now we can do the same for all the other components They will all have cost methods How should this method be implemented Suppose we have more than one condiment per beverage We can wrap one component in another Now let s take a look at the class diagram Another nice thing about Decorator You can add functionality at any time without disturbing the base object Let s think of some other uses of Decorator Lecture 26 ObjectOriented Languages and Systems 3 Chain of Responsibility HFDP 143 You know how filters in Unix are so powerful Take this one for example grep quotexecutequot find mydir name quotjavaquot awk F 39print 39 sort u I we 1 It prints the number of files in mydir that What happens At each step a request is passed along from one handler to the next Each handler can modify the request by processing what it can and then pass the request to the next handler The example in HFDP is for various email handlers that route messages to various mailboxes depending on the subject Let s take a look at the class diagram What are some other examples of Chain of Responsibility lnterpeter HFDP 145 We all knowthe general idea of an interpreter Read commands and do what they say The example in HFDP is a duck which can do one of three things Fly Quack Turn right One program for the interpreter is just right while daylight fly quack An interpreter always has some notion of compound commands or repetition CSCECE 517 Lecture Notes 2007 Edward F Gehringer Let s take a look at the class diagram of this interpreter from p 621 and the generalized class diagram Can you think of some other examples Visitor HFDP 149 Remember our discussion of overloading vs overriding from Lecture 16 and 28 of Skrien At that time we said In summary the compiler decides which overloaded method to call by looking at the declared type of the object being sent the message and the declared types of the arguments to the method call The method is chosen at runtime by dynamic method invocation using the actual value of the object being sent the message The actual classes of the arguments to the method call do not play a role This is very different from a language like CLOS which uses the actual types of the arguments to decide which method to execute Suppose we didwant the classes of the arguments to be used to determine which method to call My favorite example is doubledispatchingquot in arithmetic expressions If you add an integer and a floatingpoint number what type should the result be Assuming you have a Fraction class if you add an integer and a fraction what type should the result be If you add a floatingpoint number and a complex number what type should the result be Should eitherthe floatingpoint or complex number be able to be the receiver Should either be able to be the argument Lecture 26 ObjectOriented Languages and Systems 5 So the method called should depend both on the class of the receiver and the class of the argument How do we achieve this effect Let s saythat we implement the Sum method in all numeric classes Integer Floating Point Fraction and Complex So if we re performing an addition we invoke the Sum method of the class Now this Sum method knows that what it does actually depends on the class of its argument How does it achieve this effect This method eg in the Complex class is called something like SumFromFloatingPoint What does it do What does it return OK suppose that we have the four numeric classes mentioned above How many Sum methods do we need altogether What39s the example given in the text for Visitor Can you explain it CSCECE 517 Lecture Notes 2007 Edward F Gehringer 6 Objectoriented design discovering objects with CRC cards1 Reed Phillips President of Knowledge Systems Corporation introduces the tape Question How do distribute the responsibility across collaborating objects so that together they solve my problem Objects decompose problems Responsibility must be correctly distributed among objects Objects collaborate to solve problems The tension between the individuality of objects and their interdependence makes designing objectoriented systems a challenge Ward Cunningham developed the CRCcard technique He will demonstrate it with Kent Beck A CRC card looks like this Name Class Respons bilities Collaborators The problem is to design a defectinspection system Its purpose is to chops rolls of metal foil into sheets and to sort the sheets into two bins according to a preselected product standard Those that meet the standard go into one bin those that fail go into the other The system is equipped with a scanner a chopper and two airjets 39 The scanner works by reading the amount of light that is reflected from the foil The reflected light must be between certain values for the foil to be deemed good 1These are notes from a tape by Reed Phillips Ward Cunningham and Kent Beck used in this course by permission ofthe authors Lecture 1 ObjectOriented Languages and Systems The chopper can be commanded to drop cutting the foil into squares The foil may be chopped before it is scanned There are two airjets One pushes foil to the left one to the right By custom good foil is always thrown to the right Let s consider the process from the point of view ofthe square The square doesn t have physical existence before it is chopped Perhaps we should identify potential squares Eg quality whether or not it has been cut Square Accumulates attributes There are also two airjets There is some kind of dialogue that determines whether a square is to an airjet and whetherthe airjet applies to it An airjet knows where it is located along the production line It knows whether it is the good airjet or the bad one We are not yet sure if we want squares to be looking for airjets or airjets to be looking for squares Airjet Knows role and position Square There is also a chopper lts responsibility is to change the state of the square Chopper Square Realizes squares Operates physical device D 2000 NCSU CSCECE 517 Lecture Notes Fall 2000 There may also be a bin object that collects squares The airjet and chopper are similar in that they know the state of a square and they change position They will probably have a common superclass There is also a scanner Scanner Square Grades squares And the bin E Bin Square Tallying squares There are also other objects like the production surface the foil role and the shaft encoder The production surface knows where the other objects are It starts up stops the line lt advances all the squares that are on the surface Thus the square also has to have a position Square Accum ulates attr butes Holds current position The square is passive itjust marches along under control of the surface At each click the scanner asks what square is in position for me to scan Lecture 1 ObjectOriented Languages and Systems It also notifies devices when squares have arrived so that in the program devices don t have to check on each click whether a square is there Surface Devices Advances squares Noti es devices of square arrival Kent and Ward lay out the cards A bin is very closely associated with an airjet It is almost the same object Squares will be created good and if it flunks it stays flunked System may keep track of how many of the squares are bad For now time will march forward in units of shaft ticks Surface is saying clock tick clock tick clock tick and a square arrived When a square gets to an airjet the airjet asks whether it is a good guy or not Then the surface needs to be told that the square is no longer on it Airjet Knows role and position Square Signals departures of Suf ce squares Should the chopper precede the scanner If the chopper comes first it has to chop without knowing where the defects are so you have to make uniformsize sheets If the scanner comes first you have the potential of creating differentsize squares But then a square needs to know its size And the surface has to work in smaller units of size than one square So the system keeps making the square longer and longer as long as it is bad As soon as it finds a good place it says go back one and that s how long you are The scanner and the square jointly decide on how long the square is D 2000 NCSU CSCECE 517 Lecture Notes Fall 2000 There has to be a maximum size for a square so that the airjet can handle it Square Sur ce Accumulates attr butes Square Holds current position Stretches It is the surface that creates the square Surface Devices Advances squares Noti es devices of square arrival Creates squares We also have some passive objects Production criterion Describes required quality The production criterion is attached to a surface which queries it in order to tell chopper when to chop But every square consults it Square Sur ce Accumulates attr butes Square Holds current position Stretches Pf d9 quot criterion Every square that is created by the surface is tagged with the production criterion that was used to create it Lecture 1 ObjectOriented Languages and Systems So the production criteria can be changed in the middle of a run Now let s review incidents that show how CRC cards helped to nd the objects in the application Create objects only as they were needed Invest effort in phrasing the responsibility Determine appropriate collaborations The collaboration relationship is not necessarily symmetric Use spatial layout to show how the application fits together Stack cards to simplify design Stacking becomes a form of abstraction Develop scenarios to illustrate what can happen during operation of the system Reallocate responsibility to remove flaws in the design Using cards help you roleplay by acting out the behavior of the object D 2000 NCSU CSCECE 517 Lecture Notes Fall 2000 Design Outline for Lecture 15 Skrien 11 What do we mean by program 39 UML method in design OVE I39VleW ll Example Peer d t Why do we worry about deSIgn when writing a gra er sys em program Why isn t it enough that the Requirements analysis program works Domain analysis Usecases Suppose the code is never intended to be read by anyone else or used again Let s name some reasons that design matters Criteria for elegant software Skrien 12 Good software should be Usable Complete Efficient Robust Scalable Simple Readable Modifiable Reusable The first of these deal with correctness Lecture 15 ObjectOriented Languages and Systems The last deal with maintainability Objectoriented design methodologies An objectoriented methodology is defined as the system of principles and procedures applied to objectoriented software development Just over ten years ago there was no standard OOD methodology Then the proponents of three of the major methodologies Grady Booch James Rumbaugh and lvar Jacobson joined forces to produce the Unified Modeling Language UML The UML method in overview1 The UML method is an iterative approach In the past many softwaredevelopment methods insisted on a rigid series of steps analysis first then design The UML method allows for the reality that the development of a system is an iterative process The method encourages early coding of pieces of the system to aid in the requirementsdiscovery process The design should allow for change and discovery as the development process continues The three steps of OOAOOD Requirements analysis which provides the basic charter for the system s functions Domain analysis which provides the key logical structure of the system System design which provides the key physical structure of the system 1This discussion is adapted from Using the Beach MethodA Rational Approach by lseult White 1994 Rational CSCECE 517 Lecture Notes 2007 Edward F Gehringer 2 L Requirements System charter System function analysis statement D p 2 Domain IEE qu IEE analysis Class 39 I Usecase diagrams Inheritance diagrams diagrams Class Object SF ecifications specifications b p 3 System E design Package lt Compo sequence diagrams Class nent diagrams Architecture specifications diagrams Executable description release plans After this comes a fourth step which is not part of an OOAOOD methodology Implementation refers to the actual coding and iterative process involved in generating the actual application A use case is according to Jacobson a particular form or exemplar of usage a scenario that begins with some user of the system initiating some transaction or a sequence of interrelated events In an airline reservation system what kind of action would be a use case In a student peerreview system name some use cases Every use case describes some way of using the system Together all of the use cases specify the complete functionality of the system Lecture 15 ObjectOriented Languages and Systems Requirements analysis During requirements analysis the analyst works with end users and domain experts to enumerate the use cases that are key to the system s operation Objective Requirements analysis essentially forms a contract between the customer and the developers on what they system is to provide Deliverabes System charter outlines the responsibilities of the system System function statement outlines the key use cases of the system Domain anaysis During domain analysis an 00 model of the realworld system is developed This gives the developers enough knowledge to create a system carrying out the required functions Objective Domain analysis identifies all major objects in the domain including data and major operations The development of the model concentrates on resolving the potentially bewildering vocabulary used to define the system contradictory requirements obscure policy and varying styles of explanation and communication Good domain analysis also adds appropriate levels of abstraction CSCECE 517 Lecture Notes 2007 Edward F Gehringer 4 This allows structures to be built that will be reusable in many other domains Deliverabes Class diagrams identify key classes of the domain Inheritance diagrams show which classes inherit from other classes Do not overuse inheritance Usecase diagrams illustrate how objects will interact to carry out key functions System design During system design an effective and efficient implementation is defined Objective Select appropriate computers devices software services software units and data storage strategies Deliverabes Architectural descriptions capture major design decisions such as choice of processors language etc Executablerelease descriptions define the goals and content of successive executable release implementations Package diagrams partition the system into highlevel groupings of classes and objects Component diagrams show how the classes relate to the actual code Specify the libraries and subsystems that are integrated to make up the system Sequence diagrams which show the detailed operational logic to carry out functions Tie together usecase diagrams and class diagrams by showing how the classes collaborate to carry out a usecase Next time we will cover the fundamentals of object orientation and the UML methodology Example Peer review in Expertiza We will look at the peerreview functionality of the Expertiza system Lecture 15 ObjectOriented Languages and Systems 5 Expertizaanaysis We are going to consider a system for peer review and grading of student work The basic function of the system is to allow students to submit work and review other students work Students log in over the Web submit their work using a form and file browser are presented with a set of other students submissions to review fill out a rubric for each student s work they review potentially repeat the process of submission and review The instructor Creates each assignment for the course and posts a description decides on the review criteria the rubric assigns reviewers to authors retrieves grades after the review period is over Understanding the problem specification Notice that the program is going to have to deal with different courses and different assignments for each section Students will have to submit assignments and reviews over the Web To keep things simple we will assume that students use a file browser to pick the file to submit but we will try not to build this assumption in too deeply so we can change it later We want to encourage communication between authors and reviewers so authors should be permitted to see reviewers comments and revise their submissions in response to them CSCECE 517 Lecture Notes 2007 Edward F Gehringer What does that tell us about submissions and the relationship between submissions and reviews Another way to understand what the system is supposed to do is to take a look at some of its outputs Login screen llgtlilltm Expertiza Reusable buns a EXPERTIZA Welcome to Expertiza r r u W p er review peer review selects Login Name sll Password i Forgotten your password3 Lecture 15 ObjectOriented Languages and Systems Create an assignment 1 350 HQ Expertiza Reusable leaniiiiu ultietts tliniuuli beer review EXPERTIZA F uhnc Partial New Assignment Team asslgnment No v is Asslgnment name lhhovale demo Asslgnment l WllePe Rewewrubrlc rubrlcl Review welgnt Reviewsofsrevlevvrubrlc rubrlcl v Late Dollcv l v ill Revlevvs should be vlslble to all other revlevvers D Users must sign up before submitting D Number of rounds of review Rereview Review at allowed reiiiewallowed No v No v submission Resubmission Deadline Date amptime allowed Reiiiew allowed allowed Submissiondeadline t CK v No v39 Review deadline Rexlevvaorarevlevv deadline Save assignment 7 Back I rind l lame 1 tr it l3 Hill lgl i at D Matgh case Select an assignment gtstudentassigninent l list Moxllla riierax Eile Edlt yiew go goo mars Tools Help la http Mocalhostaooosmdent asslclrlrnerltllst vl a 30 Hg 0 Getting Started 5 Latest Headlines Expertiza Reusable leaniiiiu iilu39etts tliniuuli beer review EXPERTIZA A55lg n ments Note The number denoted With Ultminus sign in Final Grade column is the amount or penaltv applied Assignment Course Topic Current Stage tage Deadline 7 7 so ssl s Innovate demo mi on Wed Jul 11 15 0000 70400 2007 Mapping test 7 7 revlevv Wed Jul 11 18 4123 70400 2007 To begin tirst clle on an assignment from the list above CSCECE 517 Lecture Notes 2007 Edward F Gehringer Choose what function to perform imamr r quotam H Elie Edit yiew H 39 L 39 Ci G7 iD nttp iocainost3000smdent assignment wew actions 15 i Gemng Started 2 Latest Headilnes r r go gookrnarks ools deip vi 0 30 HQ Expertiza Reusable learnim nhietls thrnugh neer review EXPERTIZA Submit or Review Your work Submit and View reedback Dtners work Give reedback to others on their work ieW scores Next Ciick tne actiwtv you Wish to perform on the assignment titied Innovate demo HUD MOCainost moostudent assronrnerrt submit16 Select an assignment to review Emma ii tw A i W to le Edit Mew go gookrnarks ools eip H 6 v Ll v 5 2 y iD htto iOcainost3000revlewilst reviews 15 o Gemng Started a Latest Headilnes viceo HQ Expertiz Reusable learning nhietls thrnugh neer review til EXPERTIZA Reviews Reviewl Begin Review 2 Begin Dorie Lecture 15 ObjectOriented Languages and Systems Fill out a rubric w l newreview Mozilla Fivefox Elle Edit Mew go goo marks Iools help 4i v v 1 8 ill HttD locallwost3000fewew new review 29 vi 0 30 HQ 0 Geml lg Started E Latest Headlines Expertiza Reusable learning nlu39eets thrnugh neer review EXPERTIZA New ReVIew Submitted Files 5757MYTHsiABOULSTEMJIDLEGEisTUDENTiMDTIV pdf This paper covers a t t to engineering education Ho HO HO I believe this paper is worth of presentation at the conference l 0 Back This paper appears to be technicall sound This paper is well organized View feedback and scores vleeo HQ Expertiza Reusable learning nlu39eets thrnugh neer review EXPERTIZA Hume U f Scores Review 1 uestion Score Comment This paper covers a topic appropriate to engineering education 5 Vefv tirnelv This paper appears to be technicallv sound 3 It is a little sloppv in places This paper is well organized 4 I believe this paper is worthv of presentation at the 5 The audience would learn a lot from the author s conference experience 7 Total 17 85 Review 2 Question Score Comment This paper covers a topic appropriate to engineering educatm 3 It was rnore tirnelv about three vears ago This paper appears to be technicallv sound 5 1 see no problerns This paper is well organized 4 I believe this paper is worthv of presentation at the 3 Ithink rnanv of the audience have alreadv seen sirnilar conference developments 15 Total 75 Glade Average 6 80 Final Grad 80 CSCECE 517 Lecture Notes 2007 Edward F Gehringer Domain analysis Domain analysis seeks to identify key abstractions the classes and objects that are common to applications within a given domain ll39he first step is discovering key classes Start by underlining the nouns Don t underline nouns that refer to implementation characteristics Be aware of ambiguity aliasing and overloading Distinguish between classes and objects As candidate abstractions are discovered they are added to the data dictionary Some of the abstractions will turn out to be classes relations and attributes of other abstractions Choosing class names A good class name should be Mnemonic A singular noun Characteristic of the abstraction The inability to name a class simply and clearly is a symptom of an illdefined abstraction It can be a warning sign of incompleteness weak cohesion or strong coupling Lecture 15 ObjectOriented Languages and Systems 11 Cohesion refers to the strength of association of member data and functions of a class Coupling refers to the amount of dependency this class will have on other classes Identifying key abstractions in the Expertiza system A submission each of which is found on a Web page or a set of Web pages A review of a submission which is also on a Web page The assignment of reviewers to authors Are most of the key abstractions identified above classes Are all of them classes Are any of the terms used ambiguously Are there any synonyms that should make up one abstraction CSCECE 517 Lecture Notes 2007 Edward F Gehringer 12 Events What events are relevant to the system An instructor sets up a new course to use the system An instructor creates a new assignment A student submits a submission A student reviews someone else39s submission A student submits a revision of a submission A student fills out a rubric for a submission Usecases A usecasequot is a narrative that describes the sequence of events when an actor external to the system uses the system to complete a process They are stories of howthe system is used Based upon the events we have just listed we can develop use cases Use case Create assignment Actors Instructor Description An instructor creates an assignment specifying due dates rubrics penalties etc Let us try one or two more usecases Use case Actors Description Use case Actors Lecture 15 ObjectOriented Languages and Systems 13 Description To gain a deeper understanding of the processes and requirements for a system an expanded usecase can be developed They are often done in a conversational style between the actors and the system Let us consider the usecase of reviewing a submission Use case Review a submission Actors Student Description Student selects a submission to review types in a review and optionally a grade then submits the review Typical course of events Actor action System response 1 A student logs into the system 2 The system presents a screen listing assignments to submit or review 5 Student enters a review of the problem and optionally a grade and submits it 6 The system updates its database of reviews and displays the new review to the student The usecases in a system can be illustrated in a usecase diagram CSCECE 517 Lecture Notes 2007 Edward F Gehringer 14 PG system E Set up course Instructor Create assignment Student Submit assignment m Submit review Note that the actors are represented by stick figures and the use cases by ovals Later we will see that it is possible for one use case to refer to another by using it or extending it Individual usecases are diagramed by Student PG sequence diagrams These can be used to System show any pattern of interactions between 1 login objects 2 showScreen A In a sequence diagram the vertical dimension represents 3 selectProblem time and 7 4 showProblem the horizontal dimension represents different objects 5 enterRevieVIL A sample sequence diagram is shown at the right Of course this shows the system at only the highest level of detail In the course of design we would refine the diagram to include individual objects within the PG system Let us summarize our analysis by listing the classes that we have found in the system Lecture 15 ObjectOriented Languages and Systems 15 The next step is to flesh out the analysis by deciding on the data attributes and operations that each class will have What attributes does course need to have What attributes does assignment need What attributes does student need How about submission When we proceed to design we will also decide on methods for each CSCECE 517 Lecture Notes 2007 Edward F Gehringer 16 Exercise Requirements for the flightreservation system 9 9 9 9 9 GORD k The mission is to allow roundtrip airline tickets to be bought over the Web Each customer specifies an origination point a destination and dates for outbound and return flights The customer reserves one outbound flight and one return flight from a menu presented by the system Each choice that the system presents consists of one or more flight segments there may be a change of planes The customer may buy tickets for one or more passengers No more tickets can be sold for a flight than there are seats on the plane Each passenger is assigned to a specific seat The system calculates the total cost of the tickets by adding the cost of the individual segments lf dissatisfied with the cost the customer may select alternate flights After a customer has bought a ticket she will be emailed a confirmation Identify the key abstractions Write out a CRC card for each Outline a sample usecase Lecture 15 ObjectOriented Languages and Systems Leftover Patterns and Pattern Classification Factory Method Outline for Lecture 27 Right before we discussed Abstract Factory I Factory Method in Lecture 22 we hinted that when you IL Builder create an object you might know which kind I Proxy of object was going to be created IV Mediator V Hyweght That s the Factory Method pattern V Classifying patterns According to h n39lfan lava ranch mmiavaFactorvMethostAbstractFaotorv he basic difference between FactoryMethod and AbstractFactory is that o the FactoryMethod is called from inside the class hierarchy the abstract base class whereas 0 the AbstractFactory is used from the outside The GoFBook tries to hint at this fact by saying that FactoryMethod is quotclass basedquot whereas AbstractFactory is quotobject basedquot Their example is public class MyAbstractFactoryUser public void f Myobject o MyFactorycreateObject odoSomething public class MyFactoryMethoduser public abstract Myobject createobject public void f Myobject o createobject odoSomething Lecture 27 ObjectOriented Languages and Systems 1 Builder The purpose of the builder pattern is to Separate the construction of a compex object from its representation so that the same construction process can create different representations While Abstract Factory deals with creating a single object Builder deals with creating a composite object to specifications From httpl39avaworldwikidotcomdesignpatterns Builder separates the construction of a complex object from its representation so that the same construction process can create different representations We typically have 3 parties when we talk of builder pattern Client Director and Builder 0 Client knows what to build but does not know how to build it Director knows how to call the Builder based on different inputs from the client 0 Builder knows how to build different parts of it Builder and Factory have different intent Factory deals with products and makes switching between products easy The product is built in one go On the other hand builder can work with a single complex product Builder returns the product as a final step but as far as the Factory is concerned the product gets returned immediately Proxy HFDP Ch 11 This is another pattern that is fairly simple to understand Suppose you have a remote sewer and you want to contact it from your local application You don t want your application to have to know how to invoke the sewer CSCECE 517 Lecture Notes 2007 Edward F Gehringer So you have a stub method inside your application that looks like a local message send It is implemented by means of code that takes care of communicating with the remote object Mediator Mediator is used when you want to manage communication between different classes in a complex system Only the Mediator need have detailed knowledge of the functionalities and interfaces to these other classes Objects send messages to the Mediator when they want to communicate and the Mediator passes them on to other classes So Mediator promotes by avoiding the need for classes to know too much about other classes Flyweight Flyweight is a way for many objects to share most of their representation The purpose is to save memory The example from HFDP p 618 is a landscape program that needs to draw lots of trees It would be too inefficient to duplicate the representation of all the trees So instead the representation is stored once except for Classifying patterns HFDP p 589 There are many ways to classify patterns but the best known partitions patterns into three categories 0 Greatanal patterns provide ways of instantiating objects They make it possible for a client to create objects without involving itself in the details of how the object is to be created Lecture 27 ObjectOriented Languages and Systems 3 o Behavioral patterns relate to how classes or objects interact and how responsibility is to be divided between them 0 Structural patterns provide ways of organizing classes or objects into larger structures Let s divide our patterns into these three categories Purpose Creational Structural Behavioral We can further divide patterns based on whether they relate to classes or objects According to HFDP 0 Class patterns describe how relationships between classes are defined via inheritance Relationships in class patterns are established at compile time Objectpattems describe relationships between objects and are primarily defined by composition Relationships in object patterns are typically created at run time and are more dynamic and flexible Now let s divide our patterns into these two categories Hint Most patterns are object patterns CSCECE 517 Lecture Notes 2007 Edward F Gehringer 4 Purpose Scope Creational Structural Behavioral Class Object Lecture 27 ObjectOriented Languages and Systems Design Patterns Skrien 71 Oo design is more than deciding which classes work together to solve a problem It is more than deciding on suitable public interfaces forthese classes It also has to do with the study of how objects fit together to solve common programming problems The ways these objects fit together in program after program are called design patterns Design patterns in programming drawtheir inspiration from design patterns in architecture Back in the 1970s an architect named Christopher Alexander asked Is quality objectivequot Or is it just in the eye of the beholder 1 If an architect is going to place the doors into a room can she choose arbitrary locations Or are some locations better than others I He came up with the pattern of corner doors In his book A Timeless Way of Building Alexander said In the same way a courtyard which is properly formed helps people come to life in it Consider the forces at work in a courtyard Most fundamental of all people seek some kind of private outdoor space where they can sit under the sky see the stars enjoy the sun perhaps plant flowers This is obvious 1 Some of this lecture is taken from Design Patterns Explained A New Perspective on ObjectOriented Design by Alan Shalloway and James Trott 2002 AddisonWesley Lecture 9 ObjectOriented Languages and Systems 1 But there are subtle forces too For instance when a courtyard is too tightly enclosed has no view out people feel uncomfortable and tend to stay away they need to see out into some larger and more distant space Or again people are creatures of habit If they pass in and out of the courtyard every day in the course of their normal lives the courtyard becomes familiar a natural place to go and it is used But a courtyard with only one way in a place you go only when you want to go there is an unfamiliar place tends to stay unused people go more often to places that are familiar A pattern according to Alexander is a solution to a problem in a contextquot Each pattern describes a problem which occurs over and over again in our environment and then describes the core of the solution to that problem in such a way that you can use this solution a million times over without ever doing it the same way twice The description of a pattern involves o The name of the pattern The problem the pattern solves Howthe pattern can be implemented The constraints we have to consider in orderto implement it In the early 3990s some software developers including Ward Cunningham and Ralph Johnson happened on Alexander39s work They applied it to programming In 1995 Design Patterns Elements of Reusable ObjectOriented Software was published and the world has never been the same Why study design patterns There are several reasons to study design patterns To reuse solutions CSCECE 517 Lecture Notes 2007 Edward F Gehringer To establish common terminology To give you a higherlevel perspective on the problem They facilitate restructuring a system Several features of Ruby facilitate using design patterns In fact building blocks for some of the patterns are available as modules in the library Singleton The Singleton pattern is used to ensure that only one object of a particular class is instantiated Can you think of reasons that you might want to put a class in your program and insure that it is only instantiated once The Singleton pattern is available as a mixin in the Ruby library lncluding it in the code makes the new method private and provides an instance method used to create or access the single instance require 39singleton39 class Registry include Singleton attraccessor Val end r Registrynew throws a N oMethodError r Registryinstance Lecture 9 ObjectOriented Languages and Systems rval 5 s Registryinstance puts sval sval 6 puts rval sdup What39s the difference between require and include Let s take a look at how this might be implemented class Single def initialize Initialize an instance of the class end def selfinstance return instance if defined instance instance new end privateclassmethod new end Actually the Singleton module is more complicated than this Can you identify one or two additional things it needs to do Also notice that initialize has no arguments Why do you think this is The Singleton pattern can39t be implemented this easily in Java Why not CSCECE 517 Lecture Notes 2007 Edward F Gehringer Adapter Pattern An adapter allows classes to work together that normally could not because of incompatible interfaces lt wraps its own interface around the interface of a preexisting class What does this mean It may also translate data formats from the callerto a form needed by the callee Can you think of some examples where you would need to do this Suggest method signatures of the original class and method signatures for the new class One can implement the Adapter Pattern using delegation in Ruby Consider the following contrived example We want to put a SquarePeg into a RoundHole by passing it to the holes pegfits method The pegfits method checks the radius attribute of the peg but a SquarePeg does not have a radius Therefore we need to adapt the interface of the SquarePeg to meet the requirements of the RoundHole Lecture 9 ObjectOriented Languages and Systems 5 Class SquarePeg attrreader Width def initializewidth Width Width end end Class RoundPeg attrreader radius def initializeradius radius radius end end Class RoundHole attrreader radius def initializer radius r end def pegfitspeg pegradius lt radius end end Here is the Adapter class Class SquarePegAdapter def initializesquarepeg peg squarepeg end def radius Mad1sqrtpegwidth2 22 end end hole R0undH01enew40 4upt07 d0 i peg SquarePegAdapternew SquarePegnewit0f CSCECE 517 Lecture Notes 2007 Edward F Gehringer if h01epegfits peg puts quotpeg peg fits in hole holequot else puts quotpeg peg does not fit in hole holequot end end gtgtpeg ltSquarePegAdapter0xa03 8b10gt fits in hole ltR0undH01e0an38bd0gt gtgtpeg ltSquarePegAdapter0xa03 8990gt fits in hole ltR0undH01e0an3 8bd0gt gtgtpeg ltSquarePegAdapterOxa0388a0gt does not fit in hole ltR0undH01e0xa038bd0gt gtgtpeg ltSquarePegAdapter0xa03 8720gt does not fit in hole ltR0undHole0an3 8bd0gt Lecture 9 ObjectOriented Languages and Systems Design Patterns Observer Skrien 8 0 Skrien uses a case study ol a Outline for Lecture 23 ligurerdrawing application to introduce everal important design patterns The llgure39drawmg application l Today we will consider two ol them ll The Observer Dallem o Observer and o ModelViewController Both ol these are used to allow the GUI ol an application to communicate wnh the business loglc quot The guredrawing application Theligurerdrawing application was introduced in Section 3 8ol the text and we lirst saw it in Lecture 17 Here is the window in which the application runs lD g Notemat mere is i a toolbar across Ell s Rec the top with three tools At any given time one ol the tools will be selected When the user clicks on the canvas a new ligure ol lixed size will appear where the mouse was clicked Lecture 23 ObjectrOnented Languages and Systems Let s take just a quick look at the code We will modify it as we go along package drawerO import javaxswing import javaawt public class DrawingFrame extends JFrame public DrawingFrame superquotDrawing Applicationquot setDefaultCloseOperationEXITONCLOSE Container contentPane getContentPane JComponent drawingCanvas createDrawingCanvas contentPaneadddrawingCanvas BorderLayoutCENTER JToolBar toolbar createToolbar contentPaneaddtoolbar BorderLayoutNORTH private JComponent createDrawingCanvas JComponent drawingCanvas new JPanel drawingCanvassetPreferredSizenew Dimension400 300 drawingCanvassetBackgroundColorwhite drawingCanvassetBorder BorderFactorycreateEtchedBorder return drawingCanvas private JToolBar createToolbar JToolBar toolbar new JToolBar JButton ellipseButton new JButtonquotEllipsequot toolbaraddellipseButton JButton squareButton new JButtonquotSquarequot toolbaraddsquareButton JButton RectButton new JButtonquotRectquot CSCECE 517 Lecture Notes 2007 Edward F Gehringer toolbaraddRectButton return toolbar public static void mainString args DrawingFrame drawFrame new DrawingFrame drawFramepack drawFramesetVisib1etrue How should this application handle user input Well what kind of user input is there Clicking on a tool causes How should the canvas be informed of clicks on a tool Well should the canvas be informed directly It is the canvas s job to display the figures It would be better to have another class say CanvasEditor handle interaction with the user So it is CanvasEditor that needs to handle the interactions Let s assume that the three buttons are instances of a class called ToolButton A ToolButton is like a JButton except that it keeps track of the time when it was last clicked Here is a class diagram showing how ToolButtons relate to the CanvasEditor Lecture 23 ObjectOriented Languages and Systems a N w when it s time to draw a figure the CanvasEditor just needs to poll the buttons to determine which was clicked most recently Here s a UML collaboration diagramthat shows how this is done Names that are underlined in the diagram referto objects not classes 91 getLasClld lIucz i m Tommmn 2 getLaaclileime l 3gethaCIi1ltTime lEdEl o ToulBLmon This approach is rather awkward Why Instead of the CanvasEditor keeping track of the ToolButtonS perhaps the ToolButtonS could keep track of the CanvasEditor How would this help Here s a class diagram for this approach Canvaidnor JGQCIIdzedBLmaH ToolElMDn msJus10lldltadUnMun ToolButtuH Void ToolBunoll ISOEOE 517 Lecture Notes 2007 Edward F Gehringer However the classes ToolButton and CanvasEditor classes are still tightly coupled together Observer We can reduce the coupling by using the Observer pattern which will allow ToolButtons and CanvasEditors to be unaware of what type of objects they are communicating with The easiest way of understanding the Observer pattern is to consider its alternate name PublishSubscribe Publishers produce information that is of interest to other objects in the system An object that is interested in a piece of this information subscribes to this publisher Then when an event of interest happens in the system a publisher sends it to its subscribers Subscribers can also be thought of as observers and hence the name of the pattern In our example who39s the publisher and who39s the subscriber In Java many observer classes are called listeners Since our ToolButton no longer needs to maintain the time at which it was last clicked it can be a JButton instead Event handling for a JButton is performed by an ActionListener Here s the class diagram for that Lecture 23 ObjectOriented Languages and Systems 5 memos m m g A emuumnm se eded m un mamquot oadxanPeNmmedkve anEveM Wm Here s the actionListmmx Menace public intnxfacn ActionListanax axtands EvantListamx public void actionanfomadActionEvmAt a Here 8 me code m KhuvasEditox ma mp emems me ActionListIlAnx mlerVace public class LuNasEditox implnlnnnts ctionListnnax privatn JButton salactnd utmn instanca var public huvasEditoxJButton initiamutton I thissaiactadautton initial utton public void actionPaxfomidActionEvalAt a I snlnctid utton JButton n99tSouxc90 Here 8 me code ma regmers me observers CanvasEditox CanvasEditox n9quot CSCECESHLEEWE Nate 2001 EdwardF Cehvmgev CanvasEditor ellipseButton ellipseButt on addActionListener CanvasEditor squareButton addActionListener CanvasEdit or rectButt on addActionListener CanvasEditor Which class is it in Which method is it in How does this approach reduce coupling between the buttons and the CanvasEditor39 Here s a synopsis of the Observer pattern inlt hf elm v i l u Tl l lgj tort lf M331quot E M What other kind of user input besides clicking on drawing tools does our application need to handle Lecture 23 ObjectOriented Languages and Systems 7 These events can be handled similarly but by a different kind of listener Which Here s our first attempt at the code public void mouseClickedMouseEvent e hand1e clicks in the canvas int x egetX int y egetY JPanel canvas JPanel egetSource if currentButtongetTextequals quotE11ipsequot canvasgetGraphicsdrawOval x 30 y 20 60 40 else if currentButtongetTextequals quotRectquot canvasgetGraphicsdrawRect x 30 y 20 60 40 else if currentButtongetTextequals quotsquarequot canvasgetGraphicsdrawRect x 25 y 25 50 50 What39s not nice about this code A good way to get around this problem is to have an abstract class Figure with subclasses for the various kinds of figures The code except for accessor methods is shown below A package drawer2figure import javaawt CSCECE 517 Lecture Notes 2007 Edward F Gehringer 8 public abstract class Figure private int centerX centerY center coords private int width private int height public Figureint centerX int centerY int w int h thiscenterX centerX thiscenterY centerY thiswidth w thisheight h accessor methods public abstract void drawGraphics g public class Ellipse extends Figure public Ellipse int centerX int centerY int w int h supercenterX centerY w h public void drawGraphics g int width getWidth int height getHeight gdrawOvalgetCenterX width2 getCenterY height2 width height public class Rect extends Figure public Rect int centerX int centerY int w int h supercenterX centerY w h Lecture 23 ObjectOriented Languages and Systems 9 int width public void drawGraphics g getWidth int height getHeight gdrawRectgetCenterX width2 getCenterY height2 width height public class Square extends Rect publicSquareintcenterXint centerYint w supercenterX centerY w W Unfortunately this just moves the conditional from the mouseClickedrnthdtotheactionPerformedrn hod public void actionPerformedActionEvent e JButton currentButton JButton egetSource if currentButtongetTextequals quotEllipsequot currentFigure new Ellipse0 0 60 40 else if currentButtongetTextequals quotRectquot currentFigure new Rect0 0 60 40 else if currentButtongetTextequals quotsquarequot currentFigure new Square0 0 50 This problem can be solved by giving each of the buttons their own ActionListenerUn eadOfmakMgtheCanvasEditorthe ActionListenerforaHbu ons CSCECE 517 Lecture Notes 2007 Edward F Gehringer ellipseButtonaddActionListenercanvasEditor 3 ellipseButtonaddActionListener new ActionListener public void actionPerformedActionEvent e canvasEditorsetCurrentFigure new Ellipse0 0 60 40 Lecture 23 ObjectOriented Languages and Systems


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.