principles of software construction: objects, design, and...

47
1 17-214 Principles of Software Construction: Objects, Design, and Concurrency Part 2: Design case studies Design case study: Java Swing Charlie Garrod Chris Timperley

Upload: others

Post on 24-Sep-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

1 17-214

PrinciplesofSoftwareConstruction: Objects,Design,andConcurrencyPart2:DesigncasestudiesDesigncasestudy:JavaSwingCharlieGarrodChrisTimperley

Page 2: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

2 17-214

Administrivia

•  Readingduetoday:UMLandPatterns26.1and26.4•  Homework4bdueThursday,October17th

https://commons.wikimedia.org/wiki/File:1_carcassonne_aerial_2016.jpg

Page 3: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

3 17-214

KeyconceptsfromThursday

•  Observerdesignpattern•  Introductiontoconcurrency

–  Notenoughsynchronization:safetyfailure–  Toomuchsynchronization:livenessfailure

•  Event-basedprogramming•  IntroductiontoGUIs

Page 4: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

4 17-214

GUIprogrammingisinherentlymulti-threaded

•  Swingeventdispatchthread(EDT)handlesallGUIevents–  Mouseevents,keyboardevents,timerevents,etc.

•  Noothertime-consumingactivityallowedontheEDT–  Violatingthisrulecancauselivenessfailures

Page 5: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

5 17-214

Swinghasmanyeventlistenerinterfaces

•  ActionListener•  AdjustmentListener•  FocusListener•  ItemListener•  KeyListener

•  MouseListener•  TreeExpansionListener•  TextListener•  WindowListener•  …

classActionEvent{intwhen;StringactionCommand;intmodifiers;Objectsource();intid;…

}interfaceActionListener{voidactionPerformed(ActionEvente);

}

Page 6: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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

Page 7: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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

Page 8: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

8 17-214

Designdiscussion:DecouplingyourgamefromyourGUI

Page 9: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

9 17-214

Anarchitecturalpattern:Model-View-Controller(MVC)

Manageinputsfromuser:mouse,keyboard,etc.

Managedisplayofinformationonthescreen

Managedatarelatedtotheapplication

Model

View

Controller

Page 10: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

10 17-214

Today

•  Designcasestudy:GUIpotpourri–  Strategy–  Templatemethod–  Observer–  Composite–  Decorator–  Adapter–  Façade–  Command–  Chainofresponsibility

•  Anexerciseindesignpatterns

Page 11: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

11 17-214

Thedecoratorpatternabounds

Page 12: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

12 17-214

Thedecoratorpatternabounds

UMLfromhttps://medium.com/@dholnessii/structural-design-patterns-decorator-30f5a8c106a5

Page 13: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

13 17-214

Swinglayouts

see http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Thesimplest,anddefault,layout.Wrapsaroundwhenoutofspace.

LikeFlowLayout,butnowrapping

Moresophisticatedlayoutmanagers

Page 14: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

14 17-214

Anaïvehard-codedimplementation

•  AnewlayoutwouldrequirechangingoroverridingJPanel

classJPanel{protectedvoiddoLayout(){

switch(getLayoutType()){ caseBOX_LAYOUT:adjustSizeBox();break; caseBORDER_LAYOUT:adjustSizeBorder();break; ...}

}privateadjustSizeBox(){…}}

Page 15: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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));

Page 16: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

16 17-214

AnotherGUIdesignchallenge:nestingcontainers

•  AJFramecontainsaJPanel,whichcontainsaJPanel(and/orotherwidgets),whichcontainsaJPanel(and/orotherwidgets),whichcontains…

Page 17: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

17 17-214

Thecompositepattern

•  Problem:Collectionofobjectshasbehaviorsimilartotheindividualobjects

•  Solution:Havecollectionofobjectsandindividualobjectsimplementthesameinterface

•  Consequences:–  Clientcodecantreatcollectionasifitwereanindividualobject–  Easiertoaddnewobjecttypes–  Designmightbecometoogeneral,interfaceinsufficientlyuseful

Page 18: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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);

Page 19: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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);

Page 20: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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”);

}}…

Page 21: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

21 17-214

Betteruseoftemplatemethod:partialcustomization

JComponent:

Page 22: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

22 17-214

Eventpropagationanddeepcontainerhierarchies

Page 23: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

23 17-214

Eventpropagationanddeepcontainerhierarchies

Page 24: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

24 17-214

Eventpropagationanddeepcontainerhierarchies

Page 25: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

25 17-214

Eventpropagationanddeepcontainerhierarchies

Page 26: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

26 17-214

Eventpropagationanddeepcontainerhierarchies

Page 27: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

27 17-214

Thechainofresponsibilitypattern

•  Problem:Youneedtoassociatefunctionalitywithinadeepnestedoriterativestructure,possiblywithmultipleobjects

•  Solution:Requestforfunctionality,passrequestalongchainuntilsomecomponenthandlesit

•  Consequences:–  Decouplessenderfromreceiverofrequest–  Cansimplifyrequest-handlingbyhandlingrequestsnearrootofhierarchy–  Handlingofrequestnotguaranteed

Page 28: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

28 17-214

ThedesignofJListandJTree

•  Highlyflexiblerenderingoflistsandtrees–  Canchangerenderingofcells–  Canchangesourceofdatatodisplay

//exampleofsimpleuseString[]items={“a”,“b”,“c”};JList<String>list=newJList<>(items);

Page 29: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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);

}

Page 30: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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(…);

}

Page 31: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

31 17-214

AttachingadatasourcetoaJList

•  Assumewehaveananagramgenerator,andwewanttoupdateaJListwithnewanagramsastheyaregenerated

//design1classAnagramGenimplementsListModel<String>{

List<String>items…

intgetSize(){returnitems.size();}StringgetElementAt(intindex){ items.get(index).toString();}voidaddListDataListener(ListDataListenerl){…}…

}

Page 32: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

32 17-214

AttachingadatasourcetoaJList

•  Assumewehaveananagramgenerator,andwewanttoupdateaJListwithnewanagramsastheyaregenerated

//design2classAnagramGen{

DefaultListModel<String>items…

publicListModel<String>getListModel(){ returnitems;}publicIterable<String>getItems(){ returnitems.elements();}…

}

Page 33: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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){…}…

}

Page 34: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

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

Page 35: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

35 17-214

Theadapterpattern

•  Problem:YouhaveaclientthatexpectsoneAPIforaserviceprovider,andaserviceproviderwithadifferentAPI

•  Solution:WriteaclassthatimplementstheexpectedAPI,convertingcallstotheserviceprovider'sactualAPI

•  Consequences:–  Easyinteroperabilityofunrelatedclientsandlibraries

•  Clientcanuseunforeseenfuturelibraries–  Adapterclassiscoupledtoconcreteserviceprovider,canmakeitharder

tooverrideserviceproviderbehavior

Page 36: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

36 17-214

Theadapterpattern,illustrated

Havethis andthis? Usethis!

Page 37: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

37 17-214

Aside:Thefaçadepattern

Façade

√√

√ √

Subsystem classes

Page 38: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

38 17-214

Thefaçadevs.adapterpatterns

•  Motivation:–  Façade:ProvidesimpleinterfaceforacomplexAPI

•  Façadeinterfaceistypicallynew–  Adapter:MatchinterfaceexpectedbyanexistingclienttoexistingAPI

•  Adapterinterfaceisdefinedbytheexistingclient'sexpectations

Page 39: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

39 17-214

Today

•  Designcasestudy:GUIpotpourri–  Strategy–  Templatemethod–  Observer–  Composite–  Decorator–  Adapter–  Façade–  Command–  Chainofresponsibility

•  Anexerciseindesignpatterns

Page 40: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

40 17-214

Designpatternswehaveseensofar

Composite

Templatemethod

Strategy

Command

Iterator

Chainofresponsibility

Decorator

Adapter

Façade

Model-View-Controller

Observer

Factorymethod

Page 41: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

41 17-214

Designpatternswehaveseensofar

Composite

Templatemethod

Strategy

Command

Iterator

Chainofresponsibility

Decorator

Adapter

Façade

Model-View-Controller

Observer

Factorymethod

Page 42: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

42 17-214

Anoteondesign

•  Thepreviousexerciseisbackward–  "Here'sadesignpattern.Nowuseit."

•  Therealexercise:"HowdoIdesignthisprogramtoaccomplishmygoals?"–  "Aha!I'veseenthisproblembefore!"

Page 43: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

43 17-214

Nexttime

•  DesigncasestudyofJavaCollections

Page 44: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:

44 17-214

Paperslidesfromlecturearescannedbelow..

Page 45: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:
Page 46: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade:
Page 47: Principles of Software Construction: Objects, Design, and …charlie/courses/17-214/2019-fall/slides/... · 2019/10/8  · The façade vs. adapter patterns • Motivation: – Façade: