CS计算机代考程序代写 chain Java gui flex android cache ant Software Design and Construction 2 SOFT3202 / COMP9202 Advanced Design Patterns (GoF)

Software Design and Construction 2 SOFT3202 / COMP9202 Advanced Design Patterns (GoF)
Prof Bernhard Scholz School of Computer Science
The University of Sydney
Page 1

Agenda
– GoF Design Patterns
– Flyweight
– Bridge
– Chain of Responsibility – Proxy
The University of Sydney
Page 2

Flyweight Design Pattern
Object Structural
The University of Sydney Page 3

Flyweight Design Pattern
– Structural Design Pattern
– Used if there is a large number of similar objects
– Data of flyweight objects are immutable
– Why?
– Reduce memory footprint of application (avoid
java.lang.OutOfMemoryError)
– Reduce execution time: creation for large number of objects can be slow
– Separate states of objects into – Intrinsic state
– Extrinsic state
The University of Sydney Page 4

Motivation – Text Editor Application
– Design of document editor system
– Use objects to represents
tables/figures
– Use object for each character
The University of Sydney
Page 5

Flyweight – Motivation
– Flexibility at fine granular level – uniform formatting and processing
– Support new character set without impacting other functions (extensibility)
– Very high cost (memory)
The University of Sydney
Page 6

Motivation – Text Editor Application
– Solution
– Creation of object for each letter of the alphabet
– Shared object than can be used in multiple contexts simultaneously
– What else is important in the object state:
– Character code
– Character position (coordinates)
– Typographic style
– Intrinsic state:
– belonging naturally, and context-independent so can be shared
– shared and thus stored in the shared object
– Extrinsic state:
– state information that can vary with flyweight’s context
– cannot be shared as it depends on the context (client’s responsibility) The University of Sydney
Page 7

Text Editor Application – Flyweight Objects
– One shared flyweight object per character which can appear in different contexts in the document structure
– Characters are the intrinsic state
The University of Sydney
Page 8

Text Editor Application – Flyweight Design

The University of Sydney Page 9

Flyweight Pattern
– Object structural – Intent:
– Usesharingtosupportlargenumbersoffine-grainedobjectsefficiently
– Applicability:
– Largenumberofobjectsareused
– Storage costs are high
– Most object state can be made extrinsic
– Manygroupsofobjectsmaybereplacedbyrelativelyfewsharedobjectsonce
extrinsic state is removed
– The application does not depend on object identity
The University of Sydney Page 10

Flyweight – Structure
The University of Sydney Page 11

Flyweight – Participants & Collaboration
– Flyweight
– Interfaceforextrinsicstate
– ConcereteFlyweight
– Implements Flyweight interface adding intrinsic state
– UnsharedConcereteFlyweight
– Makesomeconcreteflyweightsubclassesunshared
– FlyweightFactory
– Createsandmanagesflyweightobjectsandensurepropersharing
– Client
– Maintainsareferencetoflyweights
The University of Sydney
Page 12

Flyweight Consequences
– Benefits
– Efficiency:savememoryatrun-time(sharingobjects,intrinsicstate)
– Consistency: centralized objects’ state
– Drawback
– Costsfordecomposingobjectsintointrinsic/extrinsicstate – Allobjectsarecontrolleduniformly
The University of Sydney
Page 13

Flyweight – Implementation
– –
Extrinsic state and efficient storage
– Ifthereareasmanydifferentkindsofextrinsicstateasthereareobjectsbefore sharing, then removing it from shared objects won’t reduce storage costs
Managing shared objects
– FlyweightFactory objects often use an associative store to let clients look up flyweight of interests
– Sharing implies reference counting or garbage collection to reclaim a flyweight’s storage when it’s no longer needed, especially when number of flyweights is large
The University of Sydney Page 14

Another Example
– Lightweight classes ant, cockroach, ant
– Insect stores common features; is the intrinsic state
Example from sourcemaking.com
The University of Sydney
Page 15

Flyweight – Related Patterns
– Flyweight often combined with the composite pattern to implement a hierarchical structure as a graph with shared nodes
• Leafnodescannotstoreapointertotheirparent(passed) – State and Strategy Patterns
– Flyweight often implement state and strategy objects as flyweights
The University of Sydney Page 16

Bridge
Object Structural
The University of Sydney Page 17

Motivating Scenario
– Portable window abstraction in a user interface toolkit
– Abstraction to allow writing applications that work in different platforms (e.g., iOS, Android)
– Design using inheritance (right diagram)
The University of Sydney
Page 18

Motivating Scenario – Design with Inheritance
– Extend window abstraction to cover different implementation, BUT:
– Implement many classes in the hierarchy
– Strong binding between abstraction and binding(client code is platform- dependent)
The University of Sydney
Page 19

Better Design – using the Bridge
The University of Sydney Page 20
Bridge

Bridge Pattern (Handle or Body)
– Avoid permanent binding between an abstraction and its implementation
– Abstractions and their implementations should be extensible
– Changes in an abstraction’s implementation should not impact its client
– Large number of classes involved
– Split into two class hierarchies (“nested generalization”)
– Share an implementation on multiple objects and make the client unaware of it
The University of Sydney Page 21

Bridge Pattern – Participants and Collaboration
The University of Sydney Page 22
Client

Bridge Pattern – Participants and Collaboration
– Abstraction
– Definestheabstraction’sinterfaceandmaintainsareferencetoanobjectoftype
Implementor
– RefinedAbstraction
– ExtendstheinterfacedefinedbyAbstraction
– Implementor
– Definestheinterfaceforimplementationclasses.
– TheImplementorinterfaceprovidesonlyprimitiveoperations,andAbstraction
defines higher-level operations based on these primitives – Concretelmplementor
– Implements the Implement or interface and defines its concrete implementation. – Client
– AbstractionforwardsclientrequeststoitsImplementorobject.
The University of Sydney Page 23

Bridge Pattern – Consequences
– Decoupling interface and implementation
– Implementationcanbeconfiguredatrun-time
– Reduce compile-time dependencies on implementation
– Better structured design
– Improveextensibility
– Abstraction and implementor can be extended independently
– Hidingimplementationdetailsfromclients – Increased complexity!
– Two hierarchies to grow and to manage The University of Sydney
Page 24

Bridge Pattern – Implementation
– One implementor
– Abstractimplementorclassisn’tnecessaryifthere’sonlyoneimplementation
– It’sstillusefulwhenachangeintheimplementationofaclassmustnotaffectits
existing clients
– Creatingtherightimplementorobjectwhenthereismorethanone
– Abstraction’sconstructorifitknowsaboutallConcereteImplementorclasses
– A collection class supports multiple implementations, decide by the collection’s size
• Uselinkedlistforasmallcollection
• Useahashtableforalargecollection
– Defaultimplementationwhichcanbechangedaccordingtousage
The University of Sydney Page 25

Bridge Pattern – Related Patterns
– Abstract Factory
– CancreateandconfigureparticularBridge
– Adapter
– Aims at making un-related classes work together (after design consideration) – Bridgefocusesonmakingabstractionandimplementationsvaryindependently
(during design)
The University of Sydney
Page 26

Chain of Responsibility (CoR)
Object Behavioural
The University of Sydney Page 27

Motivating Scenario – GUI with Help
– GUI with a help facility where a user gets help information by clicking on it
– Help information dependent on the interface’s context (context-sensitive)
– Button in dialog box vs. button in a window
– Displaygeneralhelpinfo.Abouttheimmediatecontextincasenospecifichelp
exits
The University of Sydney Page 28

GUI with Help – Potential Design
– Organize help info. according from the most specific to the most general
– Several UI objects, one per help request
– Discusstheprose/consofthisdesign.
The University of Sydney Page 29

GUI with Help – Potential Design
– It helps to serve different types of help requests
– However, the object that ultimately provides the help isn’t known explicitly
to the object that initiates the help request (strong coupling)
– So, we need a way to decouple the object that initiates the help request from those that might provide the help information
The University of Sydney
Page 30

Better Design – Chain of Responsibility (CoR)
– Provide multiple objects a chance to handle a request
– Passtherequestalongachainofobjectsuntilonehandlesit
– First object receives the request either handles it or forward it to the next candidate on the chain, and so on so forth
– The request has an implicit receiver as the requester object has no explicit knowledge of the handler object
The University of Sydney
Page 31

Better Design – Chain of Responsibility (CoR)
– Solution details
– User clicks the “Print” button’s help
(contained in PrintDialog instance)
– PrintDialog knows the object it belongs to
– The client (request issuer) has no direct reference to the object that ultimately realizes it
The University of Sydney
Page 32

Better Design – Chain of Responsibility (CoR)
– How to ensure implicit receiver?
– Eachobjectsharescommoninterfaceforhandlingrequestsandaccessingits
successors on the chain
– Classes that want to handle help requests can make HelpHandlera parent
– HelpHandler’s HandleHelp forwards the request to the success by default
– Subclasses can override this operation to provide help under the right conditions
The University of Sydney
Page 33

Chain of Responsibility Pattern
– Intent
– Avoidcouplingthesenderofarequesttoitsreceiver
– It allows more than one object a chance to handle the request
– Chain the receiving objects and pass the request along the chain until an object
handles it
– Use
– More than one object may handle a request, and the handler should be ascertained
dynamically
– Hidethereceiver(explicitly)whenarequestshouldbeissuedtooneofseveral
objects
– Thehandlingbehaviorshouldbespecifieddynamically
The University of Sydney Page 34

CoR Pattern – Structure
Class structure
Typical object structure
The University of Sydney Page 35

CoR Pattern – Participants and Collaboration
– Handler
– Defines interface for handling requests
– May implement the successor line
– ConcreteHandler
– Handlesrequestsitisresponsiblefor
– forwardstherequesttoitssuccessorifitcannothandleit
– Client
– Initiates a request which will be propagated along the chain until a
ConcereteHandler takes responsibility for handling it The University of Sydney
Page 36

CoR Pattern – Consequences
– Reduced Coupling
– Objects in the chain does not have explicit knowledge about each other
– Flexibility in distributing responsibilities among objects – Can add/change responsibilities at run-time
– Requestscouldbeunhandled
– There’s no guarantee that a request could be handled
The University of Sydney Page 37

CoR Pattern – Implementation (1)
– Declaring child management operations: which classes declare the child management operations (add, remove) in the composite class hierarchy:
– Definechildmanagementinterfaceattheclasshierarchy’sroot • Allowstreatingallcomponentsuniformly(transparent)
• Clientsmayadd/removeobjectsfromleaves(notsafe)
– Child management in the composite class
• Add/removeobjectsatthecompile-timeinstaticallytypedlanguages(safe) • Leavesandcompositeshavedifferentinterfaces(nottransparent
– Transparencyoversafety
The University of Sydney Page 38

CoR Pattern – Implementation (2)
– Child ordering
– Orderingonthechildrenofcompositeisimportantinsomedesigns
– Compositesrepresentsparsetreesthencompoundstatementscanbeinstancesofa
composite whose children must be ordered to reflect the program
– Designchildaccessandmanagementinterfacescarefullytomanagethesequence
(use iterator pattern)
The University of Sydney Page 39

CoR Pattern – Related Patterns
– Composite
– In CoR pattern, a component’s parent can act as its successor and hence the use of
Composite pattern
The University of Sydney Page 40

Proxy Design Pattern
Object Behavioural
The University of Sydney Page 41

Proxy Design Pattern
– Purpose/Intent (a.k.a. Surrogate)
– Provideasurrogateorplaceholderforanotherobjecttocontrolaccess
– Motivation
– Use a stand-in object for expensive ones to create
– Lazy access until the expensive one is really needed
– Applicability
– Whenever there is a need for a more sophisticated reference to an object than just a
simple pointer (types next)
– Benefits
– lazy access; resource control etc.
– Limitations
– semantic problems when proxied object does not exist.
– See also: Adapter, Decorator The University of Sydney
Page 42

Example
Suppose you have a WYSIWYG document preparation system (not LAT X Proxy Example: WYSIWYG E
then) that can include images in the documents. The images could be huge so it’s not a great idea to have to load them all in at once into
Suppose you have a WYSIWYG document preparation system (not LATEX then)
memory before they’re displayed: perhaps in a multi-page document they’d
that can include images in the documents. The images could be large so it’s not a great idea to have to load them all in at once into memory before they’re
not be observed even once through an editing session.
displayed: perhaps in a multi-page document they’d not be observed even once through an editing session.
The Proxy pattern helps here because it makes a surrogate or placeholder
The Proxy pattern helps here because it makes a surrogate or placeholder in in case the image needs to be displayed.
case the image needs to be displayed.
aTextDocument
image anImageProxy
filename
anImage
data
in memory
on disc
The University of Sydney Page 43
© Drinkwater, Charleston, Scholz, McGrane INFO3220: Object Oriented Design 2019 S1 34 / 1
2019 S1

Proxy Example (cont’d)
The document editor accesses images through Graphic interface; ImageProxy maintains a filename as the reference to the image, which is passed to the ImageProxy’s constructor.
WYSIWYG Example Structure
ImageProxy stores the extent (bounding box) and a reference to the real image, which will only be non-null if the image needs to be displayed (knowing the extent without displaying it helps with the page formatting).
Graphic
Draw() GetExtent() Store() Load()
DocumentEditor
Image
Draw() GetExtent() Store() Load()
imageImp extent
image
if (image == nullptr) {
image = LoadImage(fileName);
} image->Draw();
if (image == nullptr) { return extent;
}
return image->GetExtent();
ImageProxy
Draw() GetExtent() Store() Load()
imageImp extent
The University of Sydney Page 44
The document editor accesses images through Graphic interface; ImageProxy maintains a filename as the reference to the image, which is passed to the ImageProxy’s constructor.
ImageProxy stores the extent (bounding box) and a reference to the real image,
2019 S1

Proxy – Structure
WYSIWYG Example Structure
Graphic
Draw() GetExtent() Store() Load()
DocumentEditor
Image
Draw() GetExtent() Store() Load()
imageImp extent
image
if (image == nullptr) {
image = LoadImage(fileName);
} image->Draw();
if (image == nullptr) { return extent;
}
return image->GetExtent();
ImageProxy
Draw() GetExtent() Store() Load()
imageImp extent
The document editor accesses images through Graphic interface; ImageProxy maintains a filename as the reference to the image, which is passed to the ImageProxy’s constructor.
ImageProxy stores the extent (bounding box) and a reference to the real image, which will only be non-null if the image needs to be displayed (knowing the extent
without displaying it helps with the page formatting).
Page 45
The University of Sydney
© Drinkwater, Charleston, Scholz, McGrane INFO3220: Object Oriented Design 2019 S1 35 / 1
2019 S1

Proxy Structure
– Proxy
– maintainsareferencetotherealsubject
– responsibilitiesofProxydependsonvarieties
• remote proxies encode requests and their arguments and pass them to Subject;
• virtual proxies may cache information about the Subject to delay accessing the real thing;
• protection proxies handle access appropriately for different clients – Subject
– definesthecommoninterfaceforboththeRealSubjectandtheProxy – RealSubject
– definesthereal/concreteobjectthattheproxyrepresents. The University of Sydney
Page 46

References
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software. Pearson.
– OO Design, Online: [https://www.oodesign.com/bridge-pattern.html]
The University of Sydney
Page 47

W7 Tutorial: Practical Exercises/coding
W7 Lecture: Enterprise Design Patterns
Testing Assignment A2
The University of Sydney
Page 48