Advanced Software Engineering Lecture 03
Advanced Software Engineering Lecture 03
Engineering
University of Colombo
Prabha Kularathna
Software Design
Type
Description
Examples
Idioms
Specific to a
particular language,
system or tool
Scoped locking,
Lambda expressions
Design Patterns
Captures recurring
patterns at
programming level
and common
solutions applicable.
Singleton,
Strategy,
Proxy,
Observer
Architectural
Patterns
Captures recurring
patterns at
architectural level
Optimization
Principle Patterns
Documented rules
for avoiding
common design /
implementation
Caching,
Optimizing for
common case,
Passing information
Design Patterns
Design Patterns
Definition
In software engineering, a design pattern is a
general reusable solution to a commonly
occurring problem within a given context in
software design. A design pattern is not a
finished design that can be transformed
directly into source or machine code. It is a
description or template for how to solve a
problem that can be used in many different
situations.
Design Patterns
Why?
Design Patterns
Design Patterns
Gang-of-Four
Creational Patterns
Abstract
Factory
Builder
Structural
Singleton
Adapter
Patterns
A class of which only a single instance
can
exist
Match
interfaces of different classes
Bridge
Composite
Decorator
Facade
Flyweight
Behavioral Patterns
Chain of
Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
Creational Patterns
Singleton
Used to make sure theres only one instance of a
class exists at any given time in the runtime.
Creational Patterns
Singleton
May provide a global point of access to a limited
resource.
Ex: a cache of objects
May represent a single resource that is logically
singular
Ex: a class that represents underlying
application
Creational Patterns
Singleton
Can be easily achieved by having a global static
variable that is initialized at declaration, but this is
risky as:
1. Can add startup overhead since lazy loading is
not used
2. Can lead to having multiple copies for multiple
threads which is not intentional, causing almostimpossible to detect bugs
You can have thread specific singletons.
Creational Patterns
Singleton
public
public sealed
sealed class
class Singleton
Singleton
{{
private
private static
static Singleton
Singleton instance;
instance;
private
private static
static object
object lock_
lock_ == new
new object();
object();
private
private Singleton()
Singleton() {{ }}
public
public static
static Singleton
Singleton GetSingleton()
GetSingleton()
{{
lock
lock (lock_)
(lock_)
{{
if
if (instance
(instance ==
== null)
null) instance
instance == new
new Singleton();
Singleton();
}}
}}
}}
return
return instance;
instance;
Creational Patterns
Prototype
Provides a way to create a new object using the
current object as a prototype
Creational Patterns
Prototype
If the object is very simple, creating a prototype of
itself is trivial.
4th generation object oriented programming
languages (ex: Java, C#) readily provide some
useful constructs for prototype design pattern.
Cloning types:
Shallow clone: clone only the immediate
members of given object
Deep clone: clone each member of given
object, effectively copying each member object
of the object graph.
Creational Patterns
Factory Method
Provides a factory class with a method which can
return a specific concrete type of an object for
given situation.
This provides a single point of access to create an
object out of a set of concrete implementations of
an abstract class, which effectively enhances
readability & discoverability.
Creational Patterns
Factory Method
Creational Patterns
Factory Method
Creational Patterns
Factory Method
public abstract class FactoryBase
{
public abstract ProductBase FactoryMethod(ProductTypes type);
}
public class ConcreteFactory : FactoryBase
{
public override ProductBase FactoryMethod(ProductTypes type)
{
switch (type)
{
case ProductTypes.Product1:
return new ConcreteProduct1();
case ProductTypes.Product2:
return new ConcreteProduct2();
default:
throw new ArgumentException("Unsupported type.", "type"
}
}
}
Creational Patterns
Abstract Factory
A Factory object typically acts as a factory to
create a set of requested objects. Abstract Factory
design pattern provides means to have different
factory implementations for different situations,
were each factory is capable of creating the
requested object for the given situation.
Creational Patterns
Abstract Factory
Creational Patterns
Abstract Factory
public abstract class AbstractProductA { }
public class ProductA1 : AbstractProductA { }
public class ProductA2 : AbstractProductA { }
public abstract class AbstractProductB { }
public class ProductB1 : AbstractProductB { }
public class ProductB2 : AbstractProductB { }
public abstract class AbstractFactory
{
public abstract AbstractProductA CreateProductA();
public abstract AbstractProductB CreateProductB();
}
Creational Patterns
Abstract Factory
public class ConcreteFactoryA : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA1();
}
public override AbstractProductB CreateProductB()
{
return new ProductB1();
}
}
Creational Patterns
Abstract Factory
public class ConcreteFactoryB : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA2();
}
public override AbstractProductB CreateProductB()
{
return new ProductB2();
}
}
Structural Patterns
Adapter
Allows two incompatible types to communicate
Structural Patterns
Adapter
public interface ITarget
{
void MethodA();
}
public class Adaptee
{
public void MethodB()
{
Console.WriteLine("MethodB called");
}
}
public class Adapter : ITarget
{
Adaptee adaptee = new Adaptee();
public void MethodA()
{
adaptee.MethodB();
}
}
Structural Patterns
Adapter
public class Client
{
private ITarget target;
public Client(ITarget target)
{
this.target = target;
}
public void MakeRequest()
{
target.MethodA();
}
}
Structural Patterns
Composite
The composite pattern describes that a group of
objects is to be treated in the same way as a single
instance of an object. The intent of a composite is to
"compose" objects into tree structures to represent
part-whole hierarchies. Implementing the composite
pattern lets clients treat individual objects and
compositions uniformly
Structural Patterns
Composite
Structural Patterns
Composite
public class Circle
{
private int x, y, radius;
private Circle[] children;
//...
public void Move(int dx, int dy)
{
this.x += dx;
this.y += dy;
foreach(Circle child in children)
{
child.Move(dx, dy);
}
}
}
Structural Patterns
Decorator
extends the functionality of individual objects by
wrapping them with one or more decorator classes.
These decorators can modify existing members and
add new methods and properties at run-time.
Structural Patterns
Decorator
Structural Patterns
Decorator
Behavioral Patterns
Command
Encapsulates a request, with its parameters so that it can be
decoupled from the place of origin
Behavioral Patterns
Command
public interface ICommand
{
void Execute();
}
public class CopyCommand : ICommand
{
public void Execute()
{
// get text from currently focused text field & move it to
clipboard
}
}
public class PasteCommand : ICommand
{
public void Execute()
{
// if clipboard has text, paste it into currently focused text
field
Behavioral Patterns
Iterator
Defines a standard interface to iterate through a collection of
objects, without needing to understand the underlying structure of
these objects.
Behavioral Patterns
Iterator
Modern object oriented programming languages (Ex: Java / C#)
readily follow this pattern in their collection implementations
Ex:
Java: all collection classes implementing java.util.Iterator interface.
C#: all collection classes implementing
System.Collections.IEnumerator interface.
Behavioral Patterns
Observer
Enables a means to observe the state of an object, so that
whenever the state of the object changes, all objects observing
this object will be informed. This pattern allows communication
between objects in a loosely coupled manner.
Behavioral Patterns
Observer
This allows objects to simply register to observe a change in an
object, so when this change is happened, all registered objects
are informed by invoking a designated method.
For example, event handling in Java is done purely based on
observer design pattern.
Behavioral Patterns
Observer
This time, an
example from
Android!
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,
"Button Clicked",
Toast.LENGTH_SHORT).show();
}
});
return true;
}
Behavioral Patterns
Strategy
Allows to use a different algorithm (strategy) based on the
current situation.
Behavioral Patterns
Strategy
public abstract class PaymentStrategy
{
public abstract void Pay(decimal amount);
}
public class CreditCardPaymentStrategy : PaymentStrategy
{
public override void Pay(decimal amount)
{
// pay via connecting VISA / MASTERCARD banking services.
}
}
public class PayPalPaymentStrategy : PaymentStrategy
{
public override void Pay(decimal amount)
{
// pay via PayPal service.
}
}
Behavioral Patterns
Strategy
Design Patterns
Source:
www.google.com
Architectural Patterns
Architectural Patterns
Layers
Designing systems architecture as a stack of layers where
1. Each lower layer exposes it to the layer above (and
optionally, to the outside world) via a well-defined protocol.
2. Each upper layer provides a relatively higher-level of
abstraction in terms of functionality, using the lower layer.
Lower layers protocol is used to communicate with it.
3. An upper layer depends on / uses functionality of the lower
layer. Not the other way around.
High level,
coarsegrained
functionality
Low level,
fine-grained
functionality
Layer N
Layer
Layer 2
Layer 1
Architectural Patterns
Layers
Architectural Patterns
Layers
Architectural Patterns
Faade
Provides a simple, unified interface to a complex
subsystem
Architectural Patterns
Model-View-Controller
(MVC)
Heavily used when designing interactive application
architectures.
Some development platforms are inherently MVC
ASP.NET MVC
iOS applications
Architectural Patterns
Model-View-Controller
(MVC)
Maintains the
data model
associated with
the view.
For a large
application,
typically
connected with
a persistence
storage (ex:
Observes user
actions.
Makes changes
in data model /
persistence
storage and
updates View
accordingly.
Architectural Patterns
Service Locator
Architectural Patterns
Service Locator
Anti-pattern
Anti-pattern
An
An AntiPattern
AntiPattern is
is aa pattern
pattern that
that tells
tells how
how to
to go
go from
from aa problem
problem to
to aa bad
bad solution.
solution.
(Contrast
(Contrast to
to an
an AmeliorationPattern,
AmeliorationPattern, which
which is
is aa pattern
pattern that
that tells
tells how
how to
to go
go from
from
aa bad
bad solution
solution to
to aa good
good solution.)
solution.)
An
An anti-pattern
anti-pattern is
is something
something that
that looks
looks like
like aa good
good idea,
idea, but
but which
which backfires
backfires
badly
badly when
when applied.
applied.