Software Construction & Design 1
The University of Sydney Page 1
Software Design and
Construction 2
SOFT3202 / COMP9202
Introduction
Software Testing
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 copyrightprotection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
OO Principles
Design Principles
Overview of Design Patterns
GoF Design Patterns (review)
The University of Sydney Page 4
OO Principles
Review
Slides from SOFT2201 by Bernhard Scholz
The University of Sydney Page 5
OO Principles
Abstraction
Encapsulation
Polymorphism
Inheritance
The University of Sydney Page 6
Abstract Classes
Abstract Classes whose method implementations are
deferred to sub-classes
Important concept in OO
Requires own key-word abstract
No instance of an abstract class can be generated
The University of Sydney Page 7
Interfaces
Java has no multi-inheritance
Interface is a way-out (introduction of multi-inheritance via the back-door)
Interfaces is a class contract that ensures that a class implements a set of
methods.
Interfaces can inherit from other interfaces
Ensures that a class has a certain set of behavior
Interfaces are specified so that they form a directed acyclic graph
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 8
Example: Interface
// definition of interface
public interface A {
int foo(int x);
}
// class X implements interface A
class X implements A {
int foo(int x) {
return x;
}
}
The University of Sydney Page 9
Example: Interface
Inheritance in interfaces
Interface B has methods foo() and hoo()
// definition of interface
public interface A {
int foo(int x);
}
public interface B extends A{
int hoo(int x);
}
The University of Sydney Page 10
Virtual Dispatch
Methods in Java permit a late binding
Reference variable and its type does not tell which method is
really invoked
The type of reference variable and class instance may differ
Class variables may override methods of super classes
The method invoked is determined by the type of the class
instance
Binding is of great importance to understand OO
The University of Sydney Page 11
Example: Virtual Dispatch
Example:
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 12
OO Design Principles
Revisit
.
The University of Sydney Page 13
GRASP: Methodological Approach to OO Design
General Responsibility Assignment Software Patterns
The five basic principles:
Creator
Information Expert
High Cohesion
Low Coupling
Controller
The University of Sydney Page 19
Dependency
A dependency exists between two elements if changes to the
definition of one element (the supplier) may cause changes to
the other (the client)
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 20
Coupling
How strongly one element is connected to, has knowledge of, or
depends on other elements
Illustrated as dependency relationship in UML class diagram
A
E
B
C
DF
The University of Sydney Page 21
GRASP: Low Coupling Principle
Problem
How to reduce the impact of change, to support low dependency, and increase reuse?
Solution
Assign a responsibility so that coupling remains low
The University of Sydney Page 22
Cohesion
How strongly related and focused the responsibilities of an
element are
How to keep objects focused, understandable, and
manageable, and as a side effect, support Low Coupling?
Assign responsibilities so that cohesion remains high
The University of Sydney Page 25
OO Design Principles
Separate aspects of your application that vary from what does not change
Program to an interface not an implementation
Behavior delegation
Composition vs Inheritance
Composition provides a lot of flexibility and change the behavior at runtime
(the object youre composing with implements the correct behavior interface)
Quality of OO designs are evaluated based on reusability, extensibility,
and maintainability
The University of Sydney Page 29
Design Patterns Review
Revisit
Slides from SOFT2201
The University of Sydney Page 30
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
https://martinfowler.com/articles/enterprisePatterns.html
The University of Sydney Page 31
Catalogue of Design Patterns
Design Pattern Description
Microsoft
Integration
Microsoft view on integration layer, system connections and
topologies for integration
Data Model Common patterns for data modelling and useful for object
modelling
Microsoft Data Patterns on data movement; replication and synchronization
https://martinfowler.com/articles/enterprisePatterns.html
https://martinfowler.com/articles/enterprisePatterns.html
The University of Sydney Page 32
Aspects of Enterprise Software
Enterprise Application Architecture
EAA typical structured into logical layers
Some differences but some common aspects
Technology independent/dependent
Patterns of EAA
Technology independent
Core J2EE
J2EE context
Microsoft Enterprise Solution Patterns
.NET views
The University of Sydney Page 33
Aspects of Enterprise Software
Enterprise Integration
EA developed independently but needs to work together
Integration was not considered, or dependent on certain technology
Enterprise Integration Patterns
messaging
Microsoft Integration Patterns
strategies
Microsoft Data Patterns
replication and synchronization
The University of Sydney Page 34
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 35
SOFT3202 / COMP93202
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 36
Review of GoF Design
Patterns
The University of Sydney Page 37
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 structure that achieves a particular purpose
Allow evolution and change
Vary independently of other components
Provide a shared language among development communities effective
communication
The University of Sydney Page 38
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 39
Gang of Four Patterns (GoF)
Official design pattern reference
Famous and influential book about design patterns
Recommended for students who wish to become
experts
We will cover the most widely used patterns from
the book
Many other patterns but not all so popular
GoF Design Patterns Design Patterns
The University of Sydney Page 40
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
Faade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
The University of Sydney Page 41
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 43
Selecting Appropriate Design Pattern
Consider how design pattern solve a problem
Read through Each patterns 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 44
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
Faade
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 45
Design Aspects Can be Varied by Design Patterns
Purpose Pattern Aspects that can change
Behavioral
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 aggregates 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 46
Creational Patterns
The University of Sydney Page 47
Creational Patterns
Abstract the instantiation process
Make a system independent of how its objects are created, composed and
represented
Class creational pattern uses inheritance to vary the class thats instantiated
Object creational pattern delegates instantiation to another object
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 48
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
https://canvas.sydney.edu.au/courses/14614/pages/lecture-review-of-design-patterns?module_item_id=437271
The University of Sydney Page 49
Factory Method
Intent
Define an interface for creating an object, but let subclasses decide which class
to instantiate. Let a class defer instantiation to subclasses
Also known as
Virtual Constructor
Applicability
A class cannot anticipate the class objects it must create
A class wants its subclasses to specify the objects it creates
Classes delegate responsibility to one of several helper subclasses, and you
want to localize the knowledge of which helper subclass is the delegate
The University of Sydney Page 50
Factory Method Pattern Structure
The University of Sydney Page 51
Factory Method Pattern Participants
Product
Defines the interface of objects the factory method creates
ConcreteProduct
Implements the Product interface
Creator
Declares the factory method, which returns an object of type Product. Creator
may also define a default implementation of the factory method that returns a
default ConcreteProduct object
May call the factory method to create a Product object
ConcreteCreator
Overrides the factory method to return an instance of a Concrete Product
The University of Sydney Page 53
Abstract Factory
Object Creational
The University of Sydney Page 54
Abstract Factory Pattern
Intent
Provide an interface for creating families of related or dependent objects
without specifying their concrete classes
Also known as
Kit
Applicability
A system should be independent of how its products are created, composed and
represented
A system should be configured with one of multiple families of products
Family of related product objects is designed to be used together and you need
to enforce this constraint
You want to provide a class library of products, and you want to reveal just their
interfaces, not their implementation
The University of Sydney Page 55
Abstract Factory
Structure
The University of Sydney Page 56
Abstract Factory Pattern Participants
AbstractFactory
Declares an interface for operations that create abstract product objects
ConcreteFactory
Implements the operations to create concrete product objects
AbstractProduct
declares an interface for a type of product object
ConcreteProduct
defines a product object to be created by the corresponding concrete factory
Implements the AbstractProduct interface
Client
uses only interfaces declared by AbstractFactory and AbstractProduct classes.
The University of Sydney Page 57
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?
CATaxAdapter
getTaxes( Sale ) : List of TaxLineItems
MATaxAdapter
getTaxes( Sale ) : List of TaxLineItems
interface
ITaxCalculatorAdapter
getTaxes( Sale ) : List of TaxLineItems
SAPAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
GreatNorthernAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
interface
IAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
interface
IInventoryAdapter
interface
ICreditAuthorizationService
Adapter
requestApproval(CreditPayment,TerminalID, MerchantID)
The University of Sydney Page 58
Abstract Factory POS
Suppose the POS is deployed in some stores in MA, well need
MATaxAdapter, GreatNorthenAccountingAdapter,
If it is deployed in CA, well need
CATaxAdapter, SAPAccountingAdapter
The University of Sydney Page 59
Abstract Factory POS
We need several factory objects each will be responsible for creating a set of
objects
A MAFactory which will create MATaxAdapter,
GreatNorthemAccountingAdapter and so on
A CAFactory which will create CATaxAdapter, SAPAccountingAdapter
and so on
Naturally well have an abstraction which is an Abstract Factory
The University of Sydney Page 60
Abstract Factory POS
+makeTaxAdapter()
+makeAccountingAdapter()
MAFactory
+makeTaxAdapter()
+makeAccountingAdapter()
CAFactory
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();
}
..
}
+makeTaxAdapter()
+makeAccountingAdapter()
ServiceFactory abstract class Serviceactory{
public abstract ITaxCalculatorAdapter makeTaxAdapter();
public abstract IAccountingAdapter makeAccountingAdapter();
}
The University of Sydney Page 61
Abstract Factory Structure (NextGen POS
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
The University of Sydney Page 62
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
https://canvas.sydney.edu.au/courses/14614/pages/lecture-review-of-design-patterns?module_item_id=437271
The University of Sydney Page 63
Structural Patterns
The University of Sydney Page 64
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
The flexibility of object composition comes from the ability to change the
composition at run-time
The University of Sydney Page 65
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.
Faade 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 66
Adapter
Intent
Convert the interface of a class into another interface clients expect
Lets classes work together that couldnt otherwise because of
incompatible interfaces
Applicability
To use an existing class, and its interface does not match the one you need
You want to create a reusable class that cooperates with unrelated or
unforeseen classes, i.e., classes that dont necessarily have compatible interfaces
Object adapter only to use several existing subclasses, but its unpractical to
adapt their interface by sub-classing every one. An object adapter can adapt
the interface of its parent class.
The University of Sydney Page 68
Object Adapter Structure
The University of Sydney Page 69
Adapter Participants
Target
Defines the domain-specific interface that Client uses
Client
Collaborates with objects conforming to the Target interface.
Adaptee
Defines an existing interface t hat needs adapting.
Adapter
Adapts the interface of Adaptee to the Target interface
Collaborations
Clients call operations on an Adapter instance. In turn, the adapter calls Adaptec
operations that carry out the request
The University of Sydney Page 73
Object Adapter Consequences
Lets a single Adapter work with many Adaptees i.e., the Adaptee itself
and all of its subclasses (if any). The Adapter can also add functionality to all
Adaptees at once
Makes it harder to override Adaptee behavior. It will require sub-classing
adaptee and making Adapter refer to the subclass rather than the Adaptee
itself
The University of Sydney Page 75
Adapter in POS Requirements
Next Gen PoS system needs to
communicate with several external
third-party services
Tax calculators, credit authorization
services, inventory systems,
accounting systems.
Each has a different API and can not
be changed.
NextGen
Manage Users
. . .
Cashier
System
Administrator
actor
use case
communicationsystem boundary
Handle Returns
Payment
Authorization
Service
actor
Tax Calculator
actor
Accounting
System
alternate
notation for
a computer
system actor
Process Rental
actor
HR System
Cash In
Process Sale
actor
Sales Activity
System
Manage Security
Analyze Activity
Outside the system boundary
and developed and maintained by third parties
The University of Sydney Page 77
Adapter in POS Reality
Consider the TaxCalculator services
Suppose the POS system will be installed through out the country
Each state has its own way of calculating and collecting tax
California: 8.5% on almost everything
Mass: 5% on most items except grocery
Each state has its own TaxCalculator service (as a jar perhaps)
California API: List getTaxes (List allItem)
Mass API: Set computeTaxes (Set allItem)
The University of Sydney Page 78
Requirements Business Rules
Business rule (domain rule)
Dictate how a domain orbusiness may operate
Not restricted by a particular application
May apply to many applications in the same domain
Company policies, physical laws and government laws
Example:
ID Rule Changeability Source
RULE1 Tax rules. Sales require
added taxes. (POS domain)
High. Tax laws change
annually, at all government
levels
law
The University of Sydney Page 80
Adapter in POS First Attempt
Novice (straightforward) design of Sale.getTaxes method
List getTaxes (){
switch (state){
case CA:
CATax catax = new CATax();
List taxlineitem = catax.getTaxes (lineItems);
break;
case MA:
MATax matax = new MATax();
List taxlineitem = new ArrayList(matax.computeTaxes (
new HashSet(lineItems))); // type conversion required
break;
}
The University of Sydney Page 81
Adapter in POS Solution
How to make the Sale object decoupled from detailed Tax Calculation services
Reason: Sale is interested in getting the tax for each taxable item, not how taxes are
calculated in different states
Solution:
Sale defines an interface to get results on taxes
ITaxCalculatorAdapter
Any Tax Calculation Service that does not use this interface needs to find a interpreter
(Adapter) to do the translation
MassTaxAdapter, CATaxAdapter
The University of Sydney Page 82
Adapter in POS Solution
MassTaxAdapter
getTaxes( Sale ) : List of TaxLineItems
CATaxAdapter
getTaxes( Sale ) : List of TaxLineItems
interface
ITaxCalculatorAdapter
getTaxes( Sale ) : List of TaxLineItems
??>Adapter
+computeTaxes()
MATax
11
+getTaxes()
CATax
class MassTaxAdapter{
private MATax matax = newMATax();
public List getTaxes (Sale sale){
Set salesLineItem = new HashSet
(sale.getSalesLineItem);
Set temSet = matax.computeTaxes(salesLineItem);
return new ArrayList(tempSet)
}
11
Sale
*
1
The University of Sydney Page 83
The new Sale class
class Sale{
List taxLineItem;
List
ITaxCalculatorAdapter tca = ;
return tca.getTaxes(this);
}
}
The University of Sydney Page 91
Faade Pattern
Object Structural
The University of Sydney Page 92
Faade Pattern
Intent
Provide a unified interface to a set of interfaces in a subsystem. It defines a
higher-level interface that makes the subsystem easier to use
Applicability
You want to provide a simple interface to a complex subsystem
There are many dependencies between clients and the implementation classes
of an abstraction
You want to layer your subsystem. Faade would define an entry point to each
subsystem level
The University of Sydney Page 93
Faade Motivation
A facade object provides a single, simplified interface to the more general facilities of a
subsystem
The University of Sydney Page 94
Faade Structure
The University of Sydney Page 95
Faade Participants
Facade
Knows which subsystem classes are responsible for a request.
Delegates client requests to appropriate subsystem objects.
Subsystem classes
Implement subsystem functionality.
Handle work assigned by the Faade object
Have no knowledge of the facade; they keep no references to it.
Collaborations
Clients communicate with the subsystem by sending requests to Faade, which forwards
them to the appropriate subsystem object(s).
Although the subsystem objects perform the actual work, the faade may have to
do work of its own to translate its interface to subsystem interfaces
Clients that use the facade dont have to access its subsystem objects directly
The University of Sydney Page 96
Consequences
Simplify the usage of an existing subsystem by defining your own interface
Shields clients from subsystem components, reduce the number of objects that clients
deal with and make the subsystem easier to use.
Promote weak coupling between the subsystem and the clients
Vary the components of the subsystem without affecting its clients
Reduce compilation dependencies (esp. large systems) when subsystem classes change
Does not prevent applications from using subsystem classes if they need to. Choice
between ease of use and flexibility.
The University of Sydney Page 97
Faade NextGen POS
Pluggable business rules in POS (iteration 2 requirements)
Consider rules that might invalidate an action at certain point
When a new sales is created:
Business rule 1: if it will be paid by a gift card, only one item is allowed to
be purchased. Invalidate all requests of entering another item.
When a payment is made by gift certificate:
Business rule 2: balance should due back in another gift certificate.
Invalidate all requests of giving customer change either in cash or credit
card.
The University of Sydney Page 98
Faade NextGen POS Business Rules
Each store that would deploy PoS system will have different business rules
implemented differently
Not desirable to scatter the implementation of business rules all over the system
Consequence: for each installation of POS system, need to modify lots of classes
We want a design that has low impact on the existing software components.
Factor out all rules in a separate subsystem to localize the change.
The University of Sydney Page 100
Faade in POS system
Use an faade object POSRuleEngineFacade to communicate with the
business rule subsystem
Faade object is usually implemented as Singleton
public class sale{
public void makeLineItem(ProductDescription desc, int quantity){
SalesLineItem sli = new SalesLineItem (desc, quantity);
// call to
Reviews
There are no reviews yet.