程序代写代做代考 distributed system scheme flex database Software Construction & Design 1
Software Construction & Design 1
The University of Sydney Page 1
Software Construction and
Design 2
SOFT3202 / COMP9202
Enterprise & GoF Design
Patterns
School of Information Technologies
Dr. Basem Suleiman
The University of Sydney Page 2
Copyright Warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– GoF Design Patterns
– State
– Service Oriented Architecture
– Web Services
– SOAP-based Services
– Representation State Transfer (REST)
– RESTful Services
The University of Sydney Page 4
State Design Pattern
GoF
The University of Sydney Page 6
State Design Pattern
– Object behavioral
– Object relationships which can be changed dynamically at run-time
– How a group of objects can collaborate to perform a task that no single
object can do alone
– Intent
– Allow an object to change its behavior when its internal state changes
– Think finite-state-machine
The University of Sydney Page 7
Motivating Scenario
– TCP network connection
– States: Established, Listening and Closed
– TCP connection responds based on its current state
The University of Sydney Page 8
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 9
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 10
State Pattern – Participants
– Context (TCPConnection)
– Defines the interface of interest to clients
– Maintains an instance of a ConcreteState subclass that defines the current state
– State (TCPState)
– Defines an interface for encapsulating the behavior associated with a certain
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 11
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
– Clients can configure a context with State objects, so its clients don’t have to
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 12
State Pattern – Consequences
– Localizes state-specific behavior for different states
– Using data values and context operations make code maintenance difficult
– State distribution across different sub-classes useful when there are many states
– Better code structure for state-specific code (better than monolithic)
– It makes state transition explicit
– State transitions as variable assignments
– State objects can protect the context from inconsistent state
– State objects can be shared
– When the state they represent is encoded entirely in their type
The University of Sydney Page 13
State Pattern – Implementation (1)
– Defining the state transitions
– Let the state subclasses specify their successor state to make the transition
(decentralized)
– Achieves flexibility – easy to modify and extend the logic
– Introduces implementation dependencies between subclasses
– Table-based state transitions
– Look-up table that maps every possible input to a succeeding state
– Easy to modify (transition data not the program code) but:
• Less efficient than a functional call
• Harder to understand the logic (transition criteria is less explicit)
• Difficult to add actions to accompany the state transitions
The University of Sydney Page 14
State Pattern – Implementation (2)
– When to create and destroy state objects?
– Pre-create them and never destroy them
• Useful for frequent state changes (save costs of re-creating states)
• Context must keep reference to all states
– Only when they are needed and destroyed them thereafter
• States are not known at run-time and context change states frequently
The University of Sydney Page 15
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 16
State Pattern – Code Example
The University of Sydney Page 17
State Pattern – Code Example
The University of Sydney Page 18
State Pattern – Code Example
– What is the output of StateDemo?
The University of Sydney Page 20
State Pattern – Related Patterns
– Flyweight
– Explains when and how state objects can be shared
– Singleton
– State object is often implemented as Singleton
The University of Sydney Page 21
Service-Oriented
Architecture (SOA)
The University of Sydney Page 22
Service-Oriented Architecture (SOA)
“a style of software design where services are provided to the other components by
application components, through a communication protocol over a network” –
Wikipedia (May 2019)
– Paradigm, approach or style
– Can help to architect applications so that certain quality attributes are satisfied
– Services are the core of this approach
The University of Sydney Page 23
What Is A Service?
– A unit of abstracted functionality that can be accessed remotely
and consumed through abstract interface
– Logically represents a business activity/functionality with a specified
outcome
– Self-contained
– Abstracts implementation details
– May compose of one or more services
The University of Sydney Page 24
A Service-based Application
The University of Sydney Page 25
SOA – A Service-based Application
(MVS/CICS)
Bank
(Win2K3/
COM+)
Credit Card
processor
Linux/
EJB
Supplier 2
(Win2K3
.NET)
Supplier 1
(Solaris/
CORBA)
Shipper 2
Smart client app
Browser-based client
On-line retail
application
(J2EE/IIOP/JMS) Web Server
Reseller
Win2K3
EJB
User
authentication
(Win2K/
MQ)
Shipper 1
– Building large-scale integrated
applications from services
– Specific enough to have clear focus
– Integration and communication
– Platform independence
– Abstracted from end users
– Reliability and robustness
– Avoid rewriting legacy code
The University of Sydney Page 26
SOA Principles
– Boundaries are explicit
– Services are external, crossing boundaries has costs and implications
– Services are autonomous
– May be outside your control, can change
– Share schema and contract
– Not classes and implementations
– Policy-based compatibility
– Requirements stated in policies, not in code
The University of Sydney Page 27
Web Services
SOAP Services
The University of Sydney Page 28
Web Services
– Relatively standardized mechanism by which one piece of software
application can connect and communicate with another using web protocols
– It provides a simple and open way of integrating functions or data from
various systems
– It can be used within an organization and/or across the public Internet
– At least two implementations: SOAP-based vs. RESTful services
– Original design of Web Services is very application-centric in contrast to
the resource-centric Web and REST style
COMP5347 Web Application Development
The University of Sydney Page 29
Web Service Specifications
– Simple Object Access Protocol (SOAP): a messaging protocol for transferring
information (XML format)
– Web Service Description Language (WSDL): A standard for describing Web
services (XML format)
– Interfaces, methods, parameters, request, response
– Generated and consumed by tools
– Universal Description, Discovery and Integration (UDDI): a registry and protocol
for publishing and discovering web services
– Like white, Yellow and Green ‘pages’
– Not really used
– Other specifications include Security, Privacy, Reliable Messaging, Transaction,
Interoperability
– Web service specifications are occasionally referred to collectively as WS-*
COMP5347 Web Application Development
The University of Sydney Page 30
Web Service – SOAP-based Services
– A component that offers services that can be accessed through messages that
follow some particular XML-based standards
– XML messages in the protocol
– XML definitions of services
– Pass around XML documents
– Building on other XML standards
– All ‘human readable’ (for some subset of ‘humans’)
– These messages may be carried over HTTP…
– Standards are managed through W3C
– Standardise only what goes on the wire
– No programming models or APIs
The University of Sydney Page 31
Terminology
– Sender
– Receiver
– Intermediary
– A receiver that then sends the message onwards
– Ultimate Receiver
– The receiver that actually provides the service
– Does not send the message on any further
The University of Sydney Page 33
Web Services Consumption
– Find a service
– Find out how to call it
– What information it needs
– Where it is located
– Ask it to do something for you
– Invoke a service method
– And add a few useful services
– Transactions? Security? Reliability?
The University of Sydney Page 34
Calling A Service – SOAP
Envelope (Mandatory) –
Marks the start and end of a
message
Body (Mandatory) –
Data for the actual message
or document being sent
Header (Optional) –
General information about
message – e.g. authentication
and transaction management
– SOAP – Simple Object Access Protocol!
– Originally simple remote procedure calls using XML-
formatted protocol
– Envelope, header, body
– Extensible protocol
• Add new header elements for new semantics
– Very widely accepted standard
The University of Sydney Page 35
WSDL Structure
– WSDL Ports
– Describe the operations that can be performed and messages that
are involved
– WSDL Messages
– Describes the parts of a messages. A part can be seen as parameters
of a message
– WSDL Types
– Defines the data types of used by the web service
– WSDL Bindings
– Describes the message format and protocol details for each port
The University of Sydney Page 36
SOAP Example – Stock Quote
GET /StockQuote HTTP/1.1
Host: www.stockquoteserver.com
Content-Type: text/xml
Content-Length: nnnn
SOAPMethodName: Stock-Namespace-URI#GetLastTradePrice
HTTP/1.1 200 OK
Content-Type: text/xml
Content-Length: nnnn
The University of Sydney Page 37
WSDL Structure
definition of types……..
definition of a message….
definition of a port…….
definition of a binding….
The University of Sydney Page 38
Publishing and Consuming a Service
The University of Sydney Page 39
SOAP-based Services – Workflow
The University of Sydney Page 40
SOAP Services – Performance Factors
– Processor time for XML encoding/decoding
– Is XML slower than binary alternatives?
– Number and size of msgs passed around
– Does verbosity cost performance?
– Proc time taken by transport protocols
– TCP/IP and HTTP
– Network delays
– Switches, routers, …
– Others …
The University of Sydney Page 41
Web Services Stack
Connected Applications
Messaging
XML
Transports
Secure Reliable Transacted
M
e
ta
d
a
ta
Management
Business
Process …Devices Mobile
P2P EAI B2B Grid
The University of Sydney Page 42
Representation State
Transfer (REST), RESTful
Services
The University of Sydney Page 43
Representation State Transfer (REST)
– Defined by Roy Fielding in his 2000 thesis
– REpresentational State Transfer (REST, “RESTful”)
– Web and agile developer community has been working on ways to make a
‘Web’ for programs rather than people
– Adopt ideas that make WWW successful, but suited to consumption by programs
rather than human readers
– “Web-friendly”: use web technologies in ways that match what the Web expects
The University of Sydney Page 44
REST – Architectural Style
– REST is an architectural style rather than a strict protocol
– REST-style architectures consist of clients and servers
– Requests and responses are built around the transfer of representations of resources
– A resource can be essentially any coherent and meaningful concept that
may be addressed
– A representation of a resource is typically a document that captures the
current or intended state of a resource
Based on Roy Fielding’s doctoral dissertation, rephrased by Wikipedia http://en.wikipedia.org/wiki/Representational_State_Transfer
COMP5347 Web Application Development
http://en.wikipedia.org/wiki/Client_(computing)
http://en.wikipedia.org/wiki/Server_(computing)
http://en.wikipedia.org/wiki/Resource_(Web)
http://en.wikipedia.org/wiki/Representation_(systemics)
The University of Sydney Page 45
REST – The Basic Idea
HTTP Client
(e.g. web browser)
Web Server Database
GET /book/222
POST /order
301 location: /order/612
PUT /order/612
SELECT *
FROM Books
WHERE isbn=222
INSERT
INTO Orders …
UPDATE Orders
WHERE id=612
SET…
[adapted from Cesare Pautasso, http://www.pautasso.info, 2008]
The University of Sydney Page 47
REST – Stateless vs. Stateful
http://www.ibm.com/developerworks/webservices/library/ws-restful/
COMP5347 Web Application Development
http://www.ibm.com/developerworks/webservices/library/ws-restful/
The University of Sydney Page 48
REST – Design Principles
1. Resource Identification through URI
2. Uniform Interface for all resources(HTTP verbs)
– GET (Query the state)
– PUT (Modify (or create)
– POST (Create a resource, with system choosing the identifier)
– DELETE (Delete a resource)
3. “Self-Descriptive” Messages through Meta-Data
4. Hyperlinks to define the application state
– Address the resources explicitly in the request message
The University of Sydney Page 49
REST – Tenets
– Resource-based rather than service-oriented
– Addressability: interesting things (resources) should have names
– Statelessness: no stateful conversations with a resource
– Representations: a resource has state representation
– Links: resources can also contain links to other resources
– Uniform Interface: HTTP methods that do the same thing
The University of Sydney Page 51
REST – Resources
– A resource is something “interesting” in your system
– Anything like Blog posting, printer, a transaction, others
– Requests are sent to URIs (“nouns”)
– Choosing the resources and their URIs is the central design decision for making a
RESTful service
– The operations (“verbs”) are always the same simple HTTP ones (“get”,
“post”, “put”) and they act as expected
The University of Sydney Page 52
REST – Resource Representations
– We deal with representations of resources
– Not the resources themselves
• “Pass-by-value” semantics
– Representation can be in any format
• Representations like JSON or XML are good for Web-based
services
– Each resource has one or more representations
– Each resource implements the uniform HTTP interface
– Resources URIs
The University of Sydney Page 53
REST – Resource Architecture
Physical Resources
Logical Resources
Uniform Interface
(Web Server)
Resource
Representation
(e.g. XML document)
Consumer
(Web Client)
The University of Sydney Page 54
REST – Uniform Resource Identifier (URI)
– Internet Standard for resource naming and identification
– Examples:
http://tools.ietf.org/html/rfc3986
https://www.google.com/search?q=rest&start=10
– REST advocates the use of “nice” URIs…
– In most HTTP stacks URIs cannot have arbitrary length (4Kb)
URI Scheme Authority Path
Query
The University of Sydney Page 55
REST – Resource URIs
– URIs should be descriptive?
– Convey some ideas about how the underlying resources are arranged
• http://spreadsheet/cells/a2,a9
• http://jim.webber.name/2007/06.aspx
– URIs should be opaque?
– Convey no semantics, can’t infer anything from them
The University of Sydney Page 56
REST – Links
– Connectedness is good in Web-based systems
– Resource representations can contain other URIs
– Resources contain links (or URI templates) to other resources
– Links act as state transitions
– Think of resources as states in a state machine
– And links as state transitions
– Application (conversation) state is captured in terms of these states
– Server state is captured in the resources themselves, and their
underlying data stores
The University of Sydney Page 57
REST – The HTTP Verbs
– Retrieve a representation of a resource: GET
– Get metadata about an existing resource: HEAD
– Create a new resource: PUT to a new URI,
or POST and the resource will get a new system-chosen URI
– Modify an existing resource: PUT to an
existing URI
– Delete an existing resource: DELETE
– See which of the verbs the resource
understands: OPTIONS
The University of Sydney Page 58
Resource Types
– Most of the time we can differentiate between collection type of resources and
individual resource
– Revisions and revision
– Articles and article
– This can be nested and developers/architect often decide the nesting direction
– /movies/ForrestGump/actors/TomHanks
– /directors/AngLee/movies/LifeOfPi
COMP5347 Web Application Development
The University of Sydney Page 59
REST – Request URLs and Methods
Action URL path Parameters Example
Create new revision /revisions http://localhost:3000/revisions
Get all revisions /revisions http://localhost:3000/revisions
Get a revision /revisions revision_id http://localhost:3000/revisions/123
Update a revision /revisions revision_id http://localhost:3000/revisions/123
Delete a revision /revisions revision_id http://localhost:3000/revisions/123
COMP5347 Web Application Development
Request Method Use case Response
POST Add new data in a collection New data created
GET Read data from data source Data objects
PUT Update existing data Updated object
DELETE Delete an object NULL
The University of Sydney Page 60
Uniform Interface Principle (CRUD Example)
CRUD REST
CREATE PUT (user chooses the URI) or POST
(system chooses the URI)
Initialize the state of a new resource
READ GET Retrieve the current state of a resource
UPDATE PUT Modify the state of a resource
DELETE DELETE Clear a resource; afterwards the URI is no longer
valid
The University of Sydney Page 61
GET Semantics
– GET retrieves the representation of a resource
– Should not affect the resource state (idempotent)
– Shared understanding of GET semantics
– Don’t violate that understanding!
The University of Sydney Page 62
POST Semantics
– POST creates a new resource
– But the server decides on that resource’s URI
– Common human Web example: posting to a blog
–Server decides URI of posting and any comments made on that post
– Programmatic Web example: creating a new employee record
–And subsequently adding to it
The University of Sydney Page 63
POST Request and Response
– Request
POST / HTTP/1.1
Content-Type: application/xml
Host: localhost:8888
Content-Length: ….
Verb, path, and HTTP
version
Content type (XML)
Content (again XML)
– Response
201 CREATED
Location: /orders/jwebber/ABCD/2007-07-08-13-50-53
The University of Sydney Page 64
PUT Semantics
– PUT creates a new resource but the client decides on the URI
– Providing the server logic allows it
– Also used to update existing resources by overwriting them in-place
– Don’t use POST here
– Because PUT is idempotent!
The University of Sydney Page 65
PUT Request
PUT /orders/jwebber/ABCD/2007-07-08-13-50-53 HTTP/1.1
Content-Type: application/xml
Host: localhost:8888
Content-Length: ….
Verb, path and HTTP
version
Updated content
(higher buy price)
The University of Sydney Page 66
PUT Response
200 OK
Location: /orders/jwebber/ABCD/2007-07-080-13-50-53
Content-Type: application/xml
Minimalist response might
contain only status and location
The University of Sydney Page 67
DELETE Semantics
– Stop the resource from being accessible
– Logical delete, not necessarily physical
– Request
DELETE /user/jwebber HTTP/1.1
Host: example.org
– Response
200 OK
Content-Type: application/xml
jwebber
This is important for
decoupling implementation
details from resources
The University of Sydney Page 68
HEAD Semantics
– HEAD is like GET, except it only retrieves metadata
– Request
HEAD /user/jwebber HTTP/1.1
Host: example.org
– Response
200 OK
Content-Type: application/xml
Last-Modified: 2007-07-08T15:00:34Z
ETag: aabd653b-65d0-74da-bc63-4bca-ba3ef3f50432
Useful for caching,
performance
The University of Sydney Page 69
OPTIONS Semantics
– Asks which methods are supported by a resource
– Easy to spot read-only resources for example
– Request
OPTIONS /user/jwebber HTTP/1.1
Host: example.org
– Response
200 OK
Allowed: GET,HEAD,POST
You can only read and
add to this resource
The University of Sydney Page 70
HTTP Status Codes
– The HTTP status codes provide metadata about the state of resources
– They are part of what makes the Web a rich platform for building
distributed systems
– They cover five broad categories
–1xx – Metadata
–2xx – Everything’s fine
–3xx – Redirection
–4xx – Client did something wrong
–5xx – Server did a bad thing
– There are a handful of these codes that we need to know in more detail
The University of Sydney Page 71
REST Strengths
– Simplicity
– Uniform interface is immutable (harder to break clients)
– HTTP/XML is ubiquitous (goes through firewalls)
– Stateless/synchronous interaction
– More fault-tolerant
– Proven scalability
– “after all the Web works”, caching, clustered server farms for QoS
– Perceived ease of adoption (light infrastructure)
– just need a browser to get started -no need to buy WS-* middleware
– easy to use with any popular rapid-dev languages/frameworks
The University of Sydney Page 72
REST Weaknesses
– Mapping REST-style synchronous semantics on top of back end systems creates
design mismatches (when they are based on asynchronous messaging or event
driven interaction)
– Cannot yet deliver all enterprise-style “-ilities” that WS-* can
– SOAP services/WS-* provides extensive WS framework and extensions
– E.g., Security and transactions are well-supported in WS-*
– Challenging to identify and locate resources appropriately in all applications
– Semantics/Syntax description very informal (user/human oriented)
– Lack of tool support for rapid construction of clients
The University of Sydney Page 73
SOAP or RESTful Services
– Service-oriented Architectures can be implemented in different ways
– Focus should be on whatever architecture gets the job done and recognize the significant
value of open standards
– avoid being religious about any specific architectures or technologies
– SOAP and the family of WS-* specifications have their strengths and weaknesses and
will be highly suitable to some applications and positively terrible for others. Likewise
with REST.
– The decision of which to use depends entirely on the circumstances of the application.
The University of Sydney Page 74
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
– “REST in Practice”, by Jim Webber, Savas Parastatidis and Ian Robinson; O’Reilly
2010
– “Architectural Styles and the Design of Network-based Software Architectures” by R.
Fielding (PhD thesis, 2000).
http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
– Enterprise-Scale Software Architecture (COMP5348) slides
– Web Application Development (COMP5347) slides
– Wikipedia, List of Web Services Specifications.
https://en.wikipedia.org/wiki/List_of_web_service_specifications
https://en.wikipedia.org/wiki/State_pattern
https://en.wikipedia.org/wiki/List_of_web_service_specifications
The University of Sydney Page 75
W11 Tutorial: Practical
Exercises/coding
W11 Lecture: Software
Verification
Design Pattern Assignment