CS计算机代考程序代写 gui flex android Software Construction and Design 2

Software Construction and Design 2
SOFT3202 / COMP9202 Abstract Factory, State, Command, Mediator
Prof Bernhard Scholz School of Computer Science
The University of Sydney
Page 1

Agenda
– GoF Design Patterns – Abstract Factory
– State
– Command – Mediator
The University of Sydney
Page 2

Abstract Factory
Object Creational
The University of Sydney Page 3

Abstract Factory Pattern
– Intent
– Provideaninterfaceforcreatingfamiliesofrelatedordependentobjects
without specifying their concrete classes – Also known as
– Kit
– Applicability
– Asystemshouldbeindependentofhowitsproductsarecreated,composedand represented
– Asystemshouldbeconfiguredwithoneofmultiplefamiliesofproducts
– Familyofrelatedproductobjectsisdesignedtobeusedtogetherandyouneed
to enforce this constraint
– Youwanttoprovideaclasslibraryofproducts,andyouwanttorevealjusttheir interfaces, not their implementation
The University of Sydney Page 4

Abstract Factory – Structure
The University of Sydney Page 5

Abstract Factory Pattern – Participants
– AbstractFactory
– Declaresaninterfaceforoperationsthatcreateabstractproductobjects
– ConcreteFactory
– Implements the operations to create concrete product objects
– AbstractProduct
– declaresaninterfaceforatypeofproductobject
– ConcreteProduct
– definesaproductobjecttobecreatedbythecorrespondingconcretefactory – ImplementstheAbstractProductinterface
– Client
– usesonlyinterfacesdeclaredbyAbstractFactoryandAbstractProductclasses.
The University of Sydney
Page 6

Abstract Factory – POS
– Problem
– Now we have a series of adapters for all sorts of different external services
– Who should be responsible for creating the correct set?
«interface»
IT axCalculatorAdapter
getTaxes( Sale ) : List of TaxLineItems
MAT axAdapter
getTaxes( Sale ) : List of TaxLineItems
CAT axAdapter
getTaxes( Sale ) : List of TaxLineItems
«interface» IAccountingAdapter
postReceivable( CreditPayment ) postSale( Sale )

«interface» ICreditAuthorizationService Adapter
requestApproval(CreditPayment,TerminalID, MerchantID) …
«interface» IInventoryAdapter

SAPAccountingAdapter
postReceivable( CreditPayment ) postSale( Sale )

GreatNorthernAccountingAdapter
postReceivable( CreditPayment ) postSale( Sale )

The University of Sydney
Page 7

Abstract Factory – POS
– Suppose the POS is deployed in some stores in MA, we’ll need – MATaxAdapter, GreatNorthenAccountingAdapter, …
– If it is deployed in CA, we’ll need
– CATaxAdapter, SAPAccountingAdapter
The University of Sydney Page 8

Abstract Factory – POS
– We need several factory objects each will be responsible for creating a set of objects
– A MAFactory which will create MATaxAdapter, GreatNorthenAccountingAdapter and so on
– A CAFactory which will create CATaxAdapter, SAPAccountingAdapter and so on
– Naturally, we’ll have an abstraction which is an Abstract Factory
The University of Sydney
Page 9

Abstract Factory – POS
class MAFactory{
public ITaxCalculatorAdapter makeTaxAdapter(){ return new MATaxAdapter();
}
public IAccountingAdapter makeAccountingAdapter(){
return new GreatNorthenAccountingAdapter(); }
.. }
class CAFactory{
public ITaxCalculatorAdapter makeTaxAdapter(){ return new CATaxAdapter();
}
public IAccountingAdapter makeAccountingAdapter(){
return new SAPAccountingAdapter(); }
.. }
MAFactory
CAFactory
+makeTaxAdapter() +makeAccountingAdapter()
+makeTaxAdapter() +makeAccountingAdapter()
ServiceFactory
+makeTaxAdapter() +makeAccountingAdapter()
The University of Sydney Page 10
abstract class Serviceactory{
public abstract ITaxCalculatorAdapter makeTaxAdapter(); public abstract IAccountingAdapter makeAccountingAdapter();
}

Abstract Factory – Structure (NextGen POS
The University of Sydney
– AbstractFactory (ServiceFactory)
– declares an interface for operations that create
abstract products
– ConcreteFactory (MAFactory, CAFactory)
– implements the operations to create concrete product objects
– AbstractProduct (IAccountingAdapter, ITaxCalculatorAdpter)
– declares an interface for a type of product object
– Product (MATaxAdapter, CATaxAdapter, SAPAccountingAdapter, GreatNorthernAccountingAdapter)
– defines a product object to be created by the corresponding concrete factory
– implements the AbstractProduct interface
– Client (Store)
– uses interfaces declared by AbstractFactory and AbstractProduct classes
Page 11

Another Example
– Let’s assume a platform independent app
– The app requires as products – Files
– GUI
– Http Access
– Factories depending on the OS
– Create objects via abstract factory
– Concrete factory represents a platform
The University of Sydney
Page 12

UML
The University of Sydney Page 13
IPhoneGUI
File
IPhone
OSPlatform
IPhoneFile
AndroidFile
Android
GUI
AndroidGUI
Http
IPhoneHttp
AndroidHttp

State Design Pattern
Object Behavioural
The University of Sydney Page 14

State Design Pattern
– Objectbehavioral
– Object relationships which can be changed dynamically at run-time
– Howagroupofobjectscancollaboratetoperformataskthatnosingle object can do alone
– Intent
– Allow an object to change its behavior when its internal state changes
– Thinkfinite-state-machine The University of Sydney
Page 15

Motivating Scenario
– TCPnetworkconnection
– States:Established,ListeningandClosed
– TCPconnectionrespondsbasedonitscurrentstate
The University of Sydney Page 16

State Pattern – When to Use
– The state of n object drives its behavior and change its behavior dynamically at run-time
– Operations have large, multipart conditional statements that depend on the object’s state
– Repeated conditional structure
The University of Sydney Page 17

State Pattern – Structure
By State_Design_Pattern_UML_Class_Diagram.png: JoaoTrindade (talk)Original uploader was JoaoTrindade at en.wikipediaderivative work: Ertwroc (talk) – State_Design_Pattern_UML_Class_Diagram.png, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=10234908
The University of Sydney Page 18

State Pattern – Participants
– Context (TCPConnection)
– Definestheinterfaceofinteresttoclients
– MaintainsaninstanceofaConcreteStatesubclassthatdefinesthecurrentstate
– State (TCPState)
– Definesaninterfaceforencapsulatingthebehaviorassociatedwithacertain
state of the Context
– ConcreteState subclasses (TCPEstablished, TCPListen, TCPClosed)
– Each subclass implements a behavior associated with a state of the Context
The University of Sydney Page 19

State Pattern – Collaborations
– Context delegates state-specific requests to the current ConcreteState object
– A context may pass itself as an argument to the State object handling the request, so the State object access the context if necessary
– Context is the primary interface for clients
– ClientscanconfigureacontextwithStateobjects,soitsclientsdon’thaveto
deal with the State objects directly
– Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances
The University of Sydney
Page 20

State Pattern – Consequences
– Localizes state-specific behavior for different states
– Usingdatavaluesandcontextoperationsmakecodemaintenancedifficult
– Statedistributionacrossdifferentsub-classesusefulwhentherearemanystates – Bettercodestructureforstate-specificcode(betterthanmonolithic)
– It makes state transition explicit
– State transitions as variable assignments
– Stateobjectscanprotectthecontextfrominconsistentstate
– State objects can be shared
– When the state they represent is encoded entirely in their type
The University of Sydney
Page 21

State Pattern – Implementation (1)
– Defining the state transitions
– Letthestatesubclassesspecifytheirsuccessorstatetomakethetransition
(decentralized)
– Achievesflexibility–easytomodifyandextendthelogic
– Introduces implementation dependencies between subclasses
– Table-basedstatetransitions
– Look-up table that maps every possible input to a succeeding state – Easytomodify(transitiondatanottheprogramcode)but:
• Lessefficientthanafunctionalcall
• Hardertounderstandthelogic(transitioncriteriaislessexplicit) • Difficulttoaddactionstoaccompanythestatetransitions
The University of Sydney
Page 22

State Pattern – Implementation (2)
– Whentocreateanddestroystateobjects? – Pre-create them and never destroy them
• Usefulforfrequentstatechanges(savecostsofre-creatingstates) • Contextmustkeepreferencetoallstates
– Only when they are needed and destroyed them thereafter
• Statesarenotknownatrun-timeandcontextchangestatesfrequently
The University of Sydney
Page 23

State Pattern – Implementation (3)
– Using dynamic inheritance
– Changing the object’s class at run-time is not possible in most OO languages
– Delegation-based languages allow changing the delegation target at run-time
The University of Sydney Page 24

State Pattern – Code Example
The University of Sydney Page 25

State Pattern – Code Example
The University of Sydney Page 26

State Pattern – Code Example
– What is the output of StateDemo? The University of Sydney
monday TUESDAY WEDNESDAY thursday FRIDAY SATURDAY sunday
Page 27

State Pattern – Related Patterns
– Flyweight
– Explains when and how state objects can be shared
– Singleton
– StateobjectisoftenimplementedasSingleton
The University of Sydney
Page 28

Command Design Pattern
Object Behavioural
The University of Sydney Page 29

Command Pattern
– Intent
– Encapsulate a request as an object, thereby letting you parameterize clients
with different requests, queue or log requests, and support undoable operations
– Applicability
– Toparameterizeobjectsbyanactiontoperform–likecallbackfunctions
– Tospecify,queueandexecuterequestsatdifferenttimes
• Acommandobjectcanhavealifetimeindependentoftheoriginalrequest
– To support undo
• TheCommand’sExecuteoperationcanstorestateforreversingitseffectsin the command itself
The University of Sydney
Page 30

Command Pattern – Applicability
– To support logging changes so it can be applied in case of a system crash – LoadandStoreoperationsintheCommandinterfacetokeepapersistentlog
of change
– Tostructureasystemaroundhigh-leveloperationsbuiltonprimitive operations
– E.g.,transactionsystemsmaintainsetofchangestodata
– Commandshaveacommoninterfacethatinvokealltransactionsthesameway
– Also, can extend the system with new transactions
The University of Sydney Page 31

Command Pattern – Structure
The University of Sydney Page 32

Command – Structure (Participants)
– Command
– Declaresaninterfaceforexecutinganoperation
– ConcreteCommand (PasteCommand, OpenCommand)
– DefinesabindingbetweenaReceiverobjectandanaction
– Implements Execute by invoking the corresponding operation(s) on Receiver
– Client (Application)
– Creates a ConcreteCommand object and sets its receiver
– Invoker (MenuItem)
– Asks the command to carry out the request
– Receiver
– Knowshowtoperformtheoperationsassociatedwithcarryingoutarequest
The University of Sydney
Page 33

Command – Toolkits User Interface Example
– Consider a user interface toolkits that include objects like buttons and menus that carry out a request in response to user input
– The toolkit cannot implement the request in the button or menu objects; applications that use the toolkit know what should be done on which object
– Requests will be issued to objects without knowing anything about the operation being requested or the receiver of the request
The University of Sydney Page 34

Command – Example
The University of Sydney Page 35

Command – Toolkit (Paste Command)
PasteCommand allows pasting text from the clipboard into a document
The University of Sydney Page 36

Command – Toolkit (Open Command)
The University of Sydney
Page 37
OpenCommand’s Execute operation

Command – Toolkit (Sequence of Commands)
The University of Sydney
Page 38

MenuItem needs to execute a sequence of commands

– E.g., MenuItem for centering a page at normal size constructed from CenterDocCommand and NormalSizeCommand
MacroCommand class allow menuItem to execute sequence of commands

Mediator Design Pattern
Object Behavioural
The University of Sydney Page 39

Mediator
– Purpose/Intent
– Create an object that manages communications for a set of objects, promoting loose coupling and
maintaining encapsulation
– Motivation
– Allowing objects which need to communicate with one another to be decoupled by introducing an
intermediary class which handles all the communication between objects. – Applicability
– Any time you have a set of objects that can communicate in complex ways, or when reusing an object is difficult because it has many connections, or group behaviour (over a set of classes) needs to be easily customisable
– Benefits
– Limits need to subclassing communicating objects (Colleagues)
– simplifies communication protocols via clear abstraction of how the objects are communicating
– Limitations
– The Mediator itself can become very complex
– See also: Façade. The University of Sydney
Page 40

Structure
The University of Sydney Page 41

Participants
– Mediator
– definesaninterfaceforcommunicatingwithColleagueobjects
– ConcreteMediator
– implementscooperativebehaviourbycoordinatingColleagueobjects – maintainalistofitsColleagues
– Colleague
– definesaninterfaceforColleagues
– ConcreteColleague
– implementstheColleagueinterface
– knowsitsMediatorobject.
– communicateswithanotherColleaguethroughitsMediatorobject.
The University of Sydney
Page 42

References
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. 1995. Design Patterns: Elements of Reusable Object-Oriented Software. Pearson.
– Wikipedia, State Design Pattern, https://en.wikipedia.org/wiki/State_pattern
The University of Sydney Page 43