CS计算机代考程序代写 database chain Java flex distributed system concurrency algorithm interpreter Software Design and Construction 2 SOFT3202 / COMP9202 Review of Design Patterns

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

Agenda
– OO Principles
– Design Principles
– Overview of Design Patterns – GoF Design Patterns (review)
The University of Sydney
Page 2

OO Principles
Review
Slides from SOFT2201 by Bernhard Scholz
The University of Sydney Page 3

OO Principles
– Encapsulation
– Inheritance
– Variable Binding & Polymorphism – Virtual Dispatch
– Abstract Classes
– Interfaces
The University of Sydney
Page 4

Encapsulation
– Wrap data/state and methods into a class as a single unit – Multiple instances can be generated
– Protect state via setter/getter methods
class Rectangle {
double length; double width;
double getLength() { return length; } double getWidth() { return width; } double area() { return length * width; }
}
The University of Sydney Page 5

Inheritance
– Sub-class inherits from super-class: methods, variables, … – Reuse structure and behavior from super-class
– Single inheritance for classes
class Rectangle extends Object {
double length; double width;
double area() { return length * width; }
}
class ColouredRectangle extends Rectangle { int colour;
int colour() { return colour; }
}
The University of Sydney Page 6

Variable Binding, Polymorphism
– Object (on heap) has single type when created – type cannot change throughout its lifetime
– Reference Variables point to null or an object
– Type of object and type of reference variable may differ
– E.g Shape x = new Rectangle(4,2); – Understand the difference
– Runtime type vs compile-time type
– Polymorphism:
– reference variable may reference differently typed object – Must be a sub-type of
The University of Sydney
Page 7

Virtual Dispatch
– Methods in Java permit a late binding
– Methods in sub-class override methods of super classes – Virtual dispatch selects which method to invoke
public class Shape extends Object { double area() { } }
public class Rectangle extends Shape { double area() { } }

Shape X = new Shape();
Shape Y = new Rectangle();
double a1 = X.area() // invokes area of Shape double a2 = Y.area() // invokes area of Rectangle
The University of Sydney Page 8

Abstract Classes
– Method implementations are deferred to sub-classes – Requires own key-word abstract for class/method
– No instance of an abstract class can be generated
abstract class Shape extends Object { public abstract double area();
}
public class Rectangle extends Shape { double width; double length;
double area() { return width * length; }
}
The University of Sydney Page 9

Interfaces
– Java has no multi-inheritance
– Interfaceisaway-out
– introductionofmulti-inheritanceviatheback-door
– Interfaces is a class contract
– implements a set of methods.
– defines set of behavior
– Interfaces can inherit from other interfaces
– But no cyclic inheritance of interfaces
– Methods declared in an interface are always public and abstract
– Variables are permitted if they are static and final only
The University of Sydney
Page 10

Example: Interface
– Inheritance in interfaces
// definition of interface public interface A {
int foo(int x);
}
public interface B extends A{ int hoo(int x);
}
– Interface B has methods foo() and hoo()
The University of Sydney Page 11

.
OO Design Principles
Revisit
The University of Sydney Page 12

GRASP: Methodological Approach to OO Design
• General Responsibility Assignment Software Patterns
• Guidelines for assigning responsibility to classes and objects
• Document and standardize principles in OOD
• The five basic principles:
1. Creator
2. Information Expert
3. High Cohesion
4. Low Coupling
5. Controller
The University of Sydney
Page 13

GRASP: Creator Principle
• Problem
• Who creates an object A in a system?
• Solution
• Assign class B the responsibility to create an instance of class A when
• B “contains” A
• B “records” A
• B “closely uses” A
• B “has the Initializing data for” A
The University of Sydney
Page 14

GRASP: Information Expert Principle
• Problem
• When should we delegate responsibilities of methods, attributes, and so on.
• Solution
• Assign responsibility by determining the information required of responsibility
• where is it stored?
• Placing the responsibility on the class with the most information available
:A
myB:B
doOne
doTwo doThree
The University of Sydney
Page 15

Cohesion
– How strongly related and focused the responsibilities of a single class?
– How to keep objects focused, understandable, and manageable, and as a side effect, support Low Coupling?
– Assign responsibilities so that cohesion remains high – If necessary, break classes apart
The University of Sydney
Page 16

High Cohesion
– Problem
– How to keep objects focused, understandable, and manageable,
and as a side effect, support Low Coupling? – Solution
– Assign responsibilities so that cohesion remains high
The University of Sydney
Page 17

Example: Cohesion
class DateLocation {
Date date; // no cohesion between Location location; // date & location Date incDate() { return date+1; }
Location incLocation() { return location+1; }
}
Bad Cohesion!
class Date {
Date date;
Date incDate() {
return date+1; } }
class Location {
Location location; Location incLocation() {
return location+1; } }
The University of Sydney
Split state/methods!
Good Cohesion!
Page 18

Dependency
– A dependency exists between two classes if a change to one causes a change to the other
– Various reason for dependency
– Class send message to another
– One class has another as its data
– One class mention another as a parameter to an operation – One class is a superclass or interface of another
The University of Sydney
Page 19

Coupling
– How strongly one element is connected to, has knowledge of, or depends on other elements?
– Dependencies in UML class diagram:
A
C
F
The University of Sydney
Page 20
B E
D

GRASP: Low Coupling Principle
• Problem
• How to reduce the impact of change, to support low dependency, and increase
reuse? • Solution
• Assign responsibility so that coupling remains low
The University of Sydney Page 21

Coupling and Cohesion
– Coupling describes the inter-objects relationship
– Cohesion describes the intra-object relationship
– Extreme case of “coupling”
– Onlyoneclassforthewholesystem – Nocouplingatall
– Extremelylowcohesion
– Extreme case of cohesion
– Separateevenasingleconceptintoseveralclasses – Veryhighcohesion
– Extremelyhighcoupling
– Domain model helps to identify concepts
– OOD helps to assign responsibilities to proper concepts
The University of Sydney
Page 22

Design Patterns Review
Revisit
Slides from SOFT2201
The University of Sydney Page 23

Catalogue of Design Patterns
Design Pattern
Description
Gang of Four (Gof)
First and most used. Fundamental patterns OO development, but not specifically for enterprise software development.
Enterprise Application Architecture (EAA)
Layered application architecture with focus on domain logic, web, database interaction and concurrency and distribution. Database patterns (object-relational mapping issues)
Enterprise Integration
Integrating enterprise applications using effective messaging models
Core J2EE
EAA Focused on J2EE platform. Applicable to other platforms
Microsoft Enterprise Solution
MS enterprise software patterns. Web, deployment and distributed systems
https://martinfowler.com/articles/enterprisePatterns.html
The University of Sydney Page 24

Aspects of Enterprise Software
– Domain Logic
– Business rules, validations and computations
– Some systems intrinsically have complex domain logic – Regular changes as business conditions change
– EAA Patterns
– organizing domain logic
– Data Model Patterns
– Data modeling approach with examples of domains
The University of Sydney
Page 25

SOFT3202 / COMP9202
– GoF Patterns
– Flyweight, Bridge, Chain of Responsibility
– Concurrency
– Lock, Thread Pool
– Enterprise
– Lazy load, Value Object, Unit of Work (MVC, SOA)
The University of Sydney
Page 26

Review of GoF Design Patterns
The University of Sydney Page 27

Design Patterns
– Proven solutions to general design problems which can be applied to specific applications
– Not readily coded solution, but rather the solution path to a common programming problem
– Design or implementation
– Allow evolution and change
structure that achieves a particular purpose – Vary independently of other components
– Provide a shared language among development communities – effective communication
The University of Sydney
Page 28

Elements of a Pattern
– The pattern name – The problem
– When to apply the pattern – The solution
– The elements that make up the design – Consequence
– The results and trade-offs of applying the pattern The University of Sydney
Page 29

Gang of Four Patterns (GoF)
The University of Sydney Page 30
• Official design pattern reference
• Famous and influential book about design patterns • GoF Design PatternsàDesign Patterns

Design Patterns – Classification
Scope / Purpose
Creational
Structural
Behavioral
Class
Factory Method
Adapter (class)
Interpreter Template Method
Object
Abstract Factory Builder Prototype Singleton
Adapter (object) Bridge Composite Decorator Façade Flyweight
Proxy
Chain of Responsibility Command
Iterator
Mediator
Memento Observer State Strategy Visitor
The University of Sydney Page 31

Design Patterns – Classification
Describes of 23 design patterns
– Creational patterns
– Abstract the instantiation process
– Make a system independent of how its objects are created, composed and represented
– Structural patterns
– How classes and objects are composed to form larger structures
– Behavioral patterns
– Concerns with algorithms and the assignment of responsibilities between
objects
The University of Sydney Page 32

Design Patterns – Different Classification (2)
Design patterns classification based on relationships
The University of Sydney Page 33

Selecting Appropriate Design Pattern
– Consider how design pattern solve a problem
– Read through Each pattern’s intent to find relevant ones
– Study the relationship between design patterns
– Study patterns of like purpose (similarities and differences)
– Examine a cause of redesign (what might force a change to a design? Tight- coupling, difficult to change classes
– Consider what should be variable in your design (see table in next slides)
The University of Sydney Page 34

Design Aspects Can be Varied by Design Patterns
Purpose
Pattern
Aspects that can change
Creational
Abstract Factory Builder
Factory Method Prototype Singleton
families of product objects
how a composite object gets created subclass of object that is instantiated class of object that is instantiated the sole instance of a class
Structural
Adapter Bridge Composite Decorator Façade Flyweight Proxy
interface to an object
implementation of an object
structure and composition of an object responsibilities of an object without subclassing interface to a subsystem
storage costs of objects
how an object is accessed; its location
The University of Sydney Page 35

Design Aspects Can be Varied by Design Patterns
Purpose
Pattern
Aspects that can change
Behavioural
Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer
State
Strategy Template Method Visitor
object that can fulfill a request
when and how a request is fulfilled
grammar and interpretation of a language
how an aggregate’s elements are accessed, traversed
how and which objects interact with each other
what private info. is stored outside an object, & when number of objects that depend on another object; how the dependent objects stay up to date
states of an object
an algorithm
steps of an algorithm
operations that can be applied to object(s) without changing their class(es)
The University of Sydney Page 36

Creational Patterns
The University of Sydney Page 37

Creational Patterns
– Abstract the instantiation process
– Make a system independent of how its objects are created, composed and
represented
– Classcreationalpatternusesinheritancetovarytheclassthat’sinstantiated – Objectcreationalpatterndelegatesinstantiationtoanotherobject
– Becomes more important as systems evolve to depend on object composition than class inheritance
– Provides flexibility in what gets created, who creates it, how it gets created and when
– Let you configure a system with “product” objects that vary in structure and functionality
The University of Sydney Page 38

Creational Patterns
Pattern Name
Description
Abstract Factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes
Singleton
Ensure a class only has one instance, and provide global point of access to it
Factory Method
Define an interface for creating an object, but let sub-class decide which class to instantiate (class instantiation deferred to subclasses)
Builder
Separate the construction of a complex object from its representation so that the same construction process can create different representations
Prototype
Specify the kinds of objects to create using a prototype instance, and create new objects by copying this prototype
See Additional Review Slides: https://canvas.sydney.edu.au/courses/14614/pages/lecture-review-of-design-patterns?module_item_id=437271
The University of Sydney Page 39

Factory Method
– Intent
– Defineaninterfaceforcreatinganobject,butletsubclassesdecidewhichclass
to instantiate. Let a class defer instantiation to subclasses – Also known as
– VirtualConstructor – Applicability
– Aclasscannotanticipatetheclassobjectsitmustcreate
– Aclasswantsitssubclassestospecifytheobjectsitcreates
– Classesdelegateresponsibilitytooneofseveralhelpersubclasses,andyou want to localize the knowledge of which helper subclass is the delegate
The University of Sydney
Page 40

Factory Method Pattern – Structure
The University of Sydney Page 41

Factory Method Pattern – Participants
– Product
– Definestheinterfaceofobjectsthefactorymethodcreates
– ConcreteProduct
– ImplementstheProductinterface
– Creator
– Declaresthefactorymethod,whichreturnsanobjectoftypeProduct.Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object
– MaycallthefactorymethodtocreateaProductobject – ConcreteCreator
– OverridesthefactorymethodtoreturnaninstanceofaConcreteProduct
The University of Sydney Page 42

Other Creational Patterns
Pattern Name
Description
Abstract Factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes
Singleton
Ensure a class only has one instance, and provide global point of access to it
Factory Method
Define an interface for creating an object, but let sub-class decide which class to instantiate (class instantiation deferred to subclasses)
Builder
Separate the construction of a complex object from its representation so that the same construction process can create different representations
Prototype
Specify the kinds of objects to create using a prototype instance, and create new objects by copying this prototype
See Additional Review Slides: https://canvas.sydney.edu.au/courses/14614/pages/lecture-review-of-design-patterns?module_item_id=437271
The University of Sydney Page 43

Structural Patterns
The University of Sydney Page 44

Structural Patterns
– How classes and objects are composed to form larger structures
– Structural class patterns use inheritance to compose interfaces or
implementations
– Structural object patterns describe ways to compose objects to realize new functionality
– Theflexibilityofobjectcompositioncomesfromtheabilitytochangethe composition at run-time
The University of Sydney Page 45

Structural Patterns (GoF)
Pattern Name
Description
Adapter
Allow classes of incompatible interfaces to work together. Convert the interface of a class into another interface clients expect.
Façade
Provides a unified interface to a set of interfaces in a subsystem. Defines a higher-level interface that makes the subsystem easier to use.
Composite
Compose objects into tree structures to represents part-whole hierarchies. Let client treat individual objects and compositions of objects uniformly
Proxy
Provide a placeholder for another object to control access to it
Decorator
Attach additional responsibilities to an object dynamically (flexible alternative to subclassing for extending functionality)
Bridge
Decouple an abstraction from its implementation so that the two can vary independently
Flight weight
Use sharing to support large numbers of fine-grained objects efficiently
The University of Sydney Page 46

Adapter
– Intent
– Convert the interface of a class into another interface clients expect
– Classes work together that couldn’t otherwise because of incompatible interfaces
– Applicability
– Touseanexistingclass,anditsinterfacedoesnotmatchtheoneyouneed
– Youwanttocreateareusableclassthatcooperateswithunrelatedor unforeseen classes, i.e., classes that don’t necessarily have compatible interfaces
– Objectadapteronlytouseseveralexistingsubclasses,butit’sunpracticalto adapt their interface by sub-classing everyone. An object adapter can adapt the interface of its parent class.
The University of Sydney Page 47

Object Adapter – Structure
The University of Sydney Page 48

Adapter – Participants
– Target
– Definesthedomain-specificinterfacethatClientuses
– Client
– CollaborateswithobjectsconformingtotheTargetinterface
– Adaptee
– Definesanexistinginterfacethatneedsadapting
– Adapter
– AdaptstheinterfaceofAdapteetotheTargetinterface
– Collaborations
– ClientscalloperationsonanAdapterinstance.Inturn,theadaptercalls
Adaptee’s operations that carry out the request The University of Sydney
Page 49

Structural Patterns (GoF)
Pattern Name
Description
Adapter
Allow classes of incompatible interfaces to work together. Convert the interface of a class into another interface clients expect.
Façade
Provides a unified interface to a set of interfaces in a subsystem. Defines a higher-level interface that makes the subsystem easier to use.
Composite
Compose objects into tree structures to represents part-whole hierarchies. Let client treat individual objects and compositions of objects uniformly
Proxy
Provide a placeholder for another object to control access to it
Decorator
Attach additional responsibilities to an object dynamically (flexible alternative to subclassing for extending functionality)
Bridge
Decouple an abstraction from its implementation so that the two can vary independently
Flight weight
Use sharing to support large numbers of fine-grained objects efficiently
See Additional Review Slides: https://canvas.sydney.edu.au/courses/14614/pages/lecture-review-of-design-patterns?module_item_id=437271
The University of Sydney Page 50

Behavioural Design Patterns
The University of Sydney Page 51

Behavioural Patterns
– Concerned with algorithms and the assignment of responsibilities between objects
– Describe patterns of objects and class, and communication between them
– Simplify complex control flow that’s difficult to follow at run-time
– Concentrate on the ways objects are interconnected – Behavioural Class Patterns
– Use inheritance to distribute behavior between classes (algorithms and computation) – Behavioural Object Patterns
– Use object composition, rather inheritance. E.g., describing how group of peer objects cooperate to perform a task that no single object can carry out by itself
The University of Sydney
Page 52

Behavioural Patterns (GoF)
Pattern Name
Description
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable (let algorithm vary independently from clients that use it)
Observer
Define a one-to-many dependency between objects so that when one object changes, all its dependents are notified and updated automatically
Memento
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later
Command
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations
State
Allow an object to alter its behaviour when its internal state changes. The object will appear to change to its class
Visitor
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates
The University of Sydney Page 53

Behavioural Patterns (GoF)
Pattern Name
Description
Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation
State
Allow an object to alter its behaviour when its internal state changes. The object will appear to change to its class
Interpreter
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language
Visitor
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates
Other patterns; Chain of responsibility, Command, Mediator, Template Method
See Additional Review Slides: https://canvas.sydney.edu.au/courses/14614/pages/lecture-review-of-design-patterns?module_item_id=437271
The University of Sydney Page 54

Strategy Pattern
Object behavioural
The University of Sydney Page 55

Strategy
– Intent
– Defineafamilyofalgorithms,encapsulateeachone,andmakethem
interchangeable
– Letthealgorithmvaryindependentlyfromclientsthatuseit
– Known as – Policy
– Motivation
– Design for varying but related algorithms
– Ability to change these algorithms
The University of Sydney
Page 56

Strategy – Example (Text Viewer)
– Many algorithms for breaking a stream of text into lines
– Problem: hard-wiring all such algorithms into the classes that require them
– Morecomplexandhardertomaintainclients(morelinebreakingalgorithms) – Notallalgorithmswillbeneededatalltimes
The University of Sydney Page 57

Strategy – Example (Text Viewer)
Maintain & update the line breaks of text
The University of Sydney
Page 58
Different line breaking algorithms (strategies)

Strategy – Applicability
– Many related classes differ only in their behavior
– Youneeddifferentvariantofanalgorithm
– Analgorithmusesdatathatshouldbehiddenfromitsclients
– A class defines many behaviors that appear as multiple statements in its operations
The University of Sydney
Page 59

Strategy – Structure
The University of Sydney Page 60

Strategy – Participants
Participant
Goals
Strategy (Compositor)
Declares an interface common to all supported algorithms Used by context to call the algorithm defined by ConcereteStrategy
ConcereteStrategy (SimpleCompositor, TeXCompositor, etc)
Implements the algorithm using the Strategy interface
Context (Compositoion)
Is configured with a ConcereteStrategy object
Maintains a reference to a Strategy object
May define an interface that lets Strategy access its data
The University of Sydney Page 61

Strategy – Collaborations
– Strategy and Context interact to implement the chosen algorithm
– A context may pass all data required by the algorithm to the Strategy
– The context can pass itself as an argument to Strategy operations
– A context forwards requests from its clients to its strategy
– Clients usually create and pass a ConcreteStrategy object to the context;
thereafter, clients interact with the context exclusively
The University of Sydney
Page 62

References
– Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object- Oriented Analysis and Design and Iterative Development (3rd Edition). Prentice Hall PTR, Upper Saddle River, NJ, USA.
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
– Martin Folwer, Patterns In Enterprise Software, [https://martinfowler.com/articles/enterprisePatterns.html]
The University of Sydney
Page 63