Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
1 17-214
PrinciplesofSoftwareConstruction: Objects,Design,andConcurrencyPart2:DesigncasestudiesDesigncasestudy:JavaSwingCharlieGarrodChrisTimperley
2 17-214
Administrivia
• Readingduetoday:UMLandPatterns26.1and26.4• Homework4bdueThursday,October17th
https://commons.wikimedia.org/wiki/File:1_carcassonne_aerial_2016.jpg
3 17-214
KeyconceptsfromThursday
• Observerdesignpattern• Introductiontoconcurrency
– Notenoughsynchronization:safetyfailure– Toomuchsynchronization:livenessfailure
• Event-basedprogramming• IntroductiontoGUIs
4 17-214
GUIprogrammingisinherentlymulti-threaded
• Swingeventdispatchthread(EDT)handlesallGUIevents– Mouseevents,keyboardevents,timerevents,etc.
• Noothertime-consumingactivityallowedontheEDT– Violatingthisrulecancauselivenessfailures
5 17-214
Swinghasmanyeventlistenerinterfaces
• ActionListener• AdjustmentListener• FocusListener• ItemListener• KeyListener
• MouseListener• TreeExpansionListener• TextListener• WindowListener• …
classActionEvent{intwhen;StringactionCommand;intmodifiers;Objectsource();intid;…
}interfaceActionListener{voidactionPerformed(ActionEvente);
}
6 17-214
Aside:lambdasvs.explicitclassdeclarations?
//staticpublicvoidmain…JFramewindow=…JPanelpanel=newJPanel();window.setContentPane(panel);JButtonbutton=newJButton(“Clickme”);button.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){ System.out.println(“Buttonclicked”);}
});panel.add(button);window.setVisible(true);
panel to hold the button
7 17-214
Aside:lambdasvs.explicitclassdeclarations?
//staticpublicvoidmain…JFramewindow=…JPanelpanel=newJPanel();window.setContentPane(panel);JButtonbutton=newJButton(“Clickme”);button.addActionListener((e)->{
System.out.println(“Buttonclicked");});panel.add(button);window.setVisible(true);
panel to hold the button
8 17-214
Designdiscussion:DecouplingyourgamefromyourGUI
9 17-214
Anarchitecturalpattern:Model-View-Controller(MVC)
Manageinputsfromuser:mouse,keyboard,etc.
Managedisplayofinformationonthescreen
Managedatarelatedtotheapplication
Model
View
Controller
10 17-214
Today
• Designcasestudy:GUIpotpourri– Strategy– Templatemethod– Observer– Composite– Decorator– Adapter– Façade– Command– Chainofresponsibility
• Anexerciseindesignpatterns
11 17-214
Thedecoratorpatternabounds
12 17-214
Thedecoratorpatternabounds
UMLfromhttps://medium.com/@dholnessii/structural-design-patterns-decorator-30f5a8c106a5
13 17-214
Swinglayouts
see http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Thesimplest,anddefault,layout.Wrapsaroundwhenoutofspace.
LikeFlowLayout,butnowrapping
Moresophisticatedlayoutmanagers
14 17-214
Anaïvehard-codedimplementation
• AnewlayoutwouldrequirechangingoroverridingJPanel
classJPanel{protectedvoiddoLayout(){
switch(getLayoutType()){ caseBOX_LAYOUT:adjustSizeBox();break; caseBORDER_LAYOUT:adjustSizeBorder();break; ...}
}privateadjustSizeBox(){…}}
15 17-214
Abettersolution:delegatethelayoutresponsibilities
• Layoutclasses,e.g.:contentPane.setLayout(newFlowLayout());contentPane.setLayout(newGridLayout(4,2));
• Similarly,thereareborderclassestodrawtheborders,e.g.:contentPane.setBorder(newEmptyBorder(5,5,5,5));
16 17-214
AnotherGUIdesignchallenge:nestingcontainers
• AJFramecontainsaJPanel,whichcontainsaJPanel(and/orotherwidgets),whichcontainsaJPanel(and/orotherwidgets),whichcontains…
17 17-214
Thecompositepattern
• Problem:Collectionofobjectshasbehaviorsimilartotheindividualobjects
• Solution:Havecollectionofobjectsandindividualobjectsimplementthesameinterface
• Consequences:– Clientcodecantreatcollectionasifitwereanindividualobject– Easiertoaddnewobjecttypes– Designmightbecometoogeneral,interfaceinsufficientlyuseful
18 17-214
Recall:Creatingabutton
//staticpublicvoidmain…JFramewindow=…JPanelpanel=newJPanel();window.setContentPane(panel);JButtonbutton=newJButton(“Clickme”);button.addActionListener((e)->{
System.out.println(“Buttonclicked");});panel.add(button);window.setVisible(true);
19 17-214
Analternativebutton
classMyButtonextendsJButton{publicMyButton(){super(“Clickme”);}@OverrideprotectedvoidfireActionPerformed(ActionEvente){
super.fireActionPerformed(e);System.out.println(“Buttonclicked”);
}}//staticpublicvoidmain…JFramewindow=…JPanelpanel=newJPanel();window.setContentPane(panel);panel.add(newMyButton());window.setVisible(true);
20 17-214
Designdiscussion:Strategyvs.templatemethodpatterns
//staticpublicvoidmain…JFramewindow=…JPanelpanel=newJPanel();window.setContentPane(panel);JButtonbutton=newJButton(“Clickme”);button.addActionListener((e)->{
System.out.println(“Buttonclicked");});panel.add(button);window.setVisible(true);
classMyButtonextendsJButton{publicMyButton(){super(“Clickme”);}@OverrideprotectedvoidfireActionPerformed(ActionEvente){
super.fireActionPerformed(e);System.out.println(“Buttonclicked”);
}}…
21 17-214
Betteruseoftemplatemethod:partialcustomization
JComponent:
22 17-214
Eventpropagationanddeepcontainerhierarchies
23 17-214
Eventpropagationanddeepcontainerhierarchies
24 17-214
Eventpropagationanddeepcontainerhierarchies
25 17-214
Eventpropagationanddeepcontainerhierarchies
26 17-214
Eventpropagationanddeepcontainerhierarchies
27 17-214
Thechainofresponsibilitypattern
• Problem:Youneedtoassociatefunctionalitywithinadeepnestedoriterativestructure,possiblywithmultipleobjects
• Solution:Requestforfunctionality,passrequestalongchainuntilsomecomponenthandlesit
• Consequences:– Decouplessenderfromreceiverofrequest– Cansimplifyrequest-handlingbyhandlingrequestsnearrootofhierarchy– Handlingofrequestnotguaranteed
28 17-214
ThedesignofJListandJTree
• Highlyflexiblerenderingoflistsandtrees– Canchangerenderingofcells– Canchangesourceofdatatodisplay
//exampleofsimpleuseString[]items={“a”,“b”,“c”};JList<String>list=newJList<>(items);
29 17-214
UsingJListswithaListModel
• Allowsalistwidget(theview)toreacttochangesinthemodel
//withaListModelListModel<String>model=newDefaultListModel<>();model.addElement(“a”);JList<String>list=newJList<>(model);
interfaceListModel<T>{intgetSize();TgetElementAt(intindex);voidaddListDataListener(ListDataListenerl);voidremoveListDataListener(ListDataListenerl);
}
30 17-214
UsingJListswithaListModel
• Allowsalistwidget(theview)toreacttochangesinthemodel
//withaListModelListModel<String>model=newDefaultListModel<>();model.addElement(“a”);JList<String>list=newJList<>(model);
interfaceListModel<T>{intgetSize();TgetElementAt(intindex);voidaddListDataListener(ListDataListenerl);voidremoveListDataListener(ListDataListenerl);
}
interfaceListDataListenerextendsEventListener{voidintervalAdded(…);voidintervalRemoved(…);voidcontentsChanged(…);
}
31 17-214
AttachingadatasourcetoaJList
• Assumewehaveananagramgenerator,andwewanttoupdateaJListwithnewanagramsastheyaregenerated
//design1classAnagramGenimplementsListModel<String>{
List<String>items…
intgetSize(){returnitems.size();}StringgetElementAt(intindex){ items.get(index).toString();}voidaddListDataListener(ListDataListenerl){…}…
}
32 17-214
AttachingadatasourcetoaJList
• Assumewehaveananagramgenerator,andwewanttoupdateaJListwithnewanagramsastheyaregenerated
//design2classAnagramGen{
DefaultListModel<String>items…
publicListModel<String>getListModel(){ returnitems;}publicIterable<String>getItems(){ returnitems.elements();}…
}
33 17-214
AttachingadatasourcetoaJList
• Assumewehaveananagramgenerator,andwewanttoupdateaJListwithnewanagramsastheyaregenerated
//design3classAnagramAdapterimplementsListModel<String>{
privatefinalAnagramGenan;publicAnagramAdapter(AnagramGens){an=s;}
intgetSize(){returncount(an.getWords());}StringgetElementAt(intindex){ find(an.getWords(),index).toString();}voidaddListDataListener(ListDataListenerl){…}…
}
34 17-214
Comparingthethreeproposeddesigns
+getItems()-items
AnagramGen
JList
+getSize()+getElementAt()
AnagramAdapter
+getSize()+getElementAt()
«interface»ListModel
+getItems()
AnagramGen
JList
+getSize()+getElementAt()
DefaultListModel
11
+getItems()+getSize()+getElementAt()
-items
AnagramGen
JList
+getSize()+getElementAt()
«interface»ListModel
1
2
3
35 17-214
Theadapterpattern
• Problem:YouhaveaclientthatexpectsoneAPIforaserviceprovider,andaserviceproviderwithadifferentAPI
• Solution:WriteaclassthatimplementstheexpectedAPI,convertingcallstotheserviceprovider'sactualAPI
• Consequences:– Easyinteroperabilityofunrelatedclientsandlibraries
• Clientcanuseunforeseenfuturelibraries– Adapterclassiscoupledtoconcreteserviceprovider,canmakeitharder
tooverrideserviceproviderbehavior
36 17-214
Theadapterpattern,illustrated
Havethis andthis? Usethis!
37 17-214
Aside:Thefaçadepattern
Façade
√√
√
√
√
√ √
Subsystem classes
38 17-214
Thefaçadevs.adapterpatterns
• Motivation:– Façade:ProvidesimpleinterfaceforacomplexAPI
• Façadeinterfaceistypicallynew– Adapter:MatchinterfaceexpectedbyanexistingclienttoexistingAPI
• Adapterinterfaceisdefinedbytheexistingclient'sexpectations
39 17-214
Today
• Designcasestudy:GUIpotpourri– Strategy– Templatemethod– Observer– Composite– Decorator– Adapter– Façade– Command– Chainofresponsibility
• Anexerciseindesignpatterns
40 17-214
Designpatternswehaveseensofar
Composite
Templatemethod
Strategy
Command
Iterator
Chainofresponsibility
Decorator
Adapter
Façade
Model-View-Controller
Observer
Factorymethod
41 17-214
Designpatternswehaveseensofar
Composite
Templatemethod
Strategy
Command
Iterator
Chainofresponsibility
Decorator
Adapter
Façade
Model-View-Controller
Observer
Factorymethod
42 17-214
Anoteondesign
• Thepreviousexerciseisbackward– "Here'sadesignpattern.Nowuseit."
• Therealexercise:"HowdoIdesignthisprogramtoaccomplishmygoals?"– "Aha!I'veseenthisproblembefore!"
43 17-214
Nexttime
• DesigncasestudyofJavaCollections
44 17-214
Paperslidesfromlecturearescannedbelow..