SlideShare a Scribd company logo
1 of 105
Download to read offline
Lecture 05 
Design Patterns
Agenda 
 Patterns 
– History, classification, structure 
 Design Principles 
– Loosley Coupled Design Principle 
– Open-Close Principle 
 Base Patterns
Reading 
 Design Patterns 
 Observer pattern 
 Factory pattern 
 Base Patterns 
 The Open-Closed Principle
Patterns
Design Patterns 
 Design pattern is a general solution to a common 
problem in software design 
– Systematic approach for problems that reoccur in software 
development 
– Not complete solution but starting point for design 
– Not code ready to use 
– Patterns have names and definitions 
– Built on common practices 
 Patterns should not be language dependant 
– However patterns apply for types of programming 
languages
History 
 Patterns originated as an architectural concept 
“Each pattern describes a problem which occurs over 
and over again in our environment, and then 
describes the core of the solution to that problem, in 
such a way that you can use this solution a million 
times over, without ever doing it the same way twice” 
- Christopher Alexander
History 
 Landmark book from 1995:Design Patterns: 
Elements of Reusable Object-Oriented Software 
– Gang of Four (GoF) 
– Term Design Pattern is 
borrowed from the 
construction industry 
 Several books on patterns 
have been published since 
– Head First Design Patterns 
for example
Vintage Design Patterns 
 Design Patterns are like good red wine 
– You cannot appreciate them at first 
– As you study them you learn the 
difference between plonk and vintage, 
or bad and good designs 
– As you become a connoisseur you experience the 
various textures you didn’t notice before 
 Warning: 
– Once you are hooked, you will no longer be satisfied 
with inferior designs 
Dr. Heinz Kabutz (http://www.javaspecialists.co.za)
Pattern Classification 
 Design patterns can be classified based on 
multiple criteria 
– Basic underlying problem they solve 
 Classification 
– Fundamental patterns 
– Creational patterns 
– Structural patterns 
– Behavioral patterns 
– Concurrency patterns
Enterprise Patterns Classification 
 Domain Logic Patterns 
 Data Source Architectural Patterns 
 Object-Relational Behavioral Patterns 
 Object-Relational Structural Patterns 
 Object-Relational Metadata Mapping Patterns 
 Web Presentation Patterns 
 Distribution Patterns 
 Offline Concurrency Patterns 
 Session State Patterns 
 Base Patterns
QUIZ 
Which of these statements is not true 
A) Design Patterns are based on solutions from practice 
B) Design Patterns are ideas not code 
C) Design Patterns are based on specific programming languages 
D) Design Patterns can have ambiguous names
QUIZ 
Which of these statements is not true 
A) Design Patterns are based on solutions from practice 
B) Design Patterns are ideas not code 
C) Design Patterns are based on specific programming languages 
D) Design Patterns can have ambiguous names 
✔
Structure of Patterns
Structure of Patterns 
 Name 
 The Intent 
 The Sketch 
 Motivation 
 How it Works 
 When to Use it 
 Further Reading 
 Examples
The Name 
 Pattern names are important 
– Need to create a vocabulary 
– Need to describe the pattern well 
– Avoid ambiguity and misunderstanding 
 Problems with names 
– Authors are using different names for same pattern 
• Data Access Object and Table Data Gateway 
• Dependency Injection and Inversion of Control 
– Authors are using same name for different patterns 
• Example: Value Object is used for two similar patterns
The Intent 
 Sums up the pattern in a sentence or two 
– Value Object: 
A small simple object, like money or date range, whose 
equality isn’t based on identity
The Sketch 
 Visual representation of the pattern, often but 
not always a UML diagram
Motivation 
 Description of a motivating problem for the 
pattern 
– Problem description 
– May not be the only problem for the pattern 
 Example: 
– Layered supertype 
It’s not uncommon for all the objects in a layer to have 
methods you don’t want to have duplicated 
throughout the system. You can move this behavior 
into a common Layer Supertype
How it Works 
 Describes the solution 
– Implementation Issues 
– Variations 
– Independent of any particular platform 
– Platform dependent sections are identified 
– UML Diagrams if applicable 
 Plugin example
When to Use It 
 Describes when the pattern should be used 
– Trade-offs 
– Comparisons 
 Layered Supertype example 
– Use Layer Supertype when you have common 
features from all objects in a layer
Examples 
 Example code in Java or C# 
– Layer Supertype 
 Not working code 
– pseudo code to give idea 
class DomainObject... 
private Long ID; 
public Long getID() 
{ 
return ID; 
} 
public void setID(Long ID) 
{ 
this.ID = ID; 
} 
public DomainObject(Long ID) 
{ 
this.ID = ID; 
}
Using Design Patterns 
 How to use design patterns? 
– Problem is the patterns can be complex and detailed 
– Usually they are generic and abstract 
 Ways to study patterns 
– Implement them in test code 
– Sketch a class diagram in your context to see the 
class dependencies 
– Form a “Study group” to discuss the patterns 
– Learn the vocabulary 
– Practice, practice, practice
Problems with Patterns 
 Ambiguity in Vocabulary 
– Same pattern has different names 
– Different Patterns have same name 
 Appling the wrong pattern 
– Over-designing the solution 
– Patterns design for one language might not be 
needed in another 
 Not solving the original problem 
– Using Remote Façade instead of avoiding network 
latencies 
– Using EJB Entity Beans
EXERCISE 
Job interview question 
You are given the assignment of creating a component that needs to 
know sales statistics of Lottery tickets. You know that there is a 
another component in the system, Sale Server, that handles the sale. 
You need real-time information. What would you suggest?
First proposal: Sale Server will call Bingo 
Sale server Bingo 
Problem is that the Sale Server developer refuses to make a call to 
a specific game. His argument is that Sale Server should be for 
sale, and not be cluttered with game specific code. 
Another solution is needed.
registerObserver 
Sale server notify 
Bingo
The Observer Pattern
The Weather Monitoring Example 
 The Weather Monitoring application
The Weather Monitoring Example 
 Task 
– We need to implement measurementsChanged so 
that it updates three different displays for current 
conditions, weather stats, and forcasts 
– measurementsChanged is called any time data 
changes, we don’t know or care how this method is 
called 
– Three display types must be updated 
– The system must be expandable – new display types 
will be added
The Weather Monitoring Example 
 WeatherData class 
public class WeatherData 
{ 
// instance variable declarations 
public void measurementsChanged() 
{ 
float temp = getTemperature(); 
float humidity = getHumidity(); 
float pressure = getPressure(); 
currentConditionsDisplay.update (temp, humidity, pressure); 
statisticsDisplay.update (temp, humidity, pressure); 
forcastConditionsDisplay.update (temp, humidity, pressure); 
} 
... 
}
QUIZ 
 Based on our first implementation, which of the 
following apply 
A. We are coding to concrete implementation not 
abstractions 
B. For every new display element we need to alter code 
C. We have no way to add (or remove) display elements at 
runtime 
D. The display elements don’t implement a common 
interface 
E. We have not encapsulated the part that changes 
F. We are violating encapsulation of the WeatherData 
class
The Weather Monitoring Example 
 WeatherData class 
public class WeatherData 
{ 
// instance variable declarations 
public void measurementsChanged() 
{ 
float temp = getTemperature(); 
float humidity = getHumidity(); 
float pressure = getPressure(); 
Interface is that same for 
all 
currentConditionsDisplay.update (temp, humidity, pressure); 
statisticsDisplay.update (temp, humidity, pressure); 
forcastConditionsDisplay.update (temp, humidity, pressure); 
} 
... 
} 
By coding to concreate implementation 
we have no way to add or remove 
displays without code change
Observer 
One or more observers or listeners are registered to 
observe an event which may be raised by the 
observed object (the subject) 
 Sometimes called publish/subscribe 
– Similar to call-back handlers 
– One-to-Many relationship 
 Benefits 
– Listening object gets information when needed 
– Subject does not become dependent on multiple observers
Observer Design Pattern
Observer Design Pattern 
 Subject does not depend on listeners
Loose Coupling 
 When two object are loosley coupled, the can 
interact but they have very little knowledge of each 
other 
 The Observer Pattern loosley coupled design 
– The only thing the subject knows about observer is that it 
implements a ceratain interface 
– We can add new observers at any time 
– We never need to modify the subject to add new types of 
observers 
– We can reuse subjects or observers independent of each 
other
Loosley Coupled Principle 
Strive for loosely coupled 
designs between objects 
that interact
Weather Station Example 
public interface Subject 
{ 
public void registerObserver(Observer o); 
public void removeObserver(Observer o); 
public void notifyObservers(); 
} 
public interface Observer 
{ 
public void update(float temp, float humidity, float pressure); 
public interface DisplayElement 
{ 
public void display(); 
} 
}
Weather Station Example 
public class WeatherData implements Subject 
{ 
private ArrayList observers; 
private float temperature, humidity, pressure; 
public WeatherData() 
{ 
observers = new ArrayList(); 
} 
public void registerObserver(Observer o) 
{ 
observers.add(o); 
} 
public void removeObserver(Observer o) 
{ 
int i = observers.indexOf(o); 
if (i>= 0) 
observers.remove(i); 
}
Weather Station Example 
public void notifyObservers() 
{ 
for (int i = 0; i<observers.size(); i++) { 
Observer observer = (Observer)observers.get(i); 
observer.update(temperature, humidity, pressure); 
} 
} 
public void measurementsChanged() 
{ 
notifyObservers(); 
} 
// Test code 
public void setMeasurement(float temperature, float humidity, 
float pressure) { 
this.temperature = temperature; 
this.humidity = humidity; 
this.pressure = pressure; 
this.measurementsChanged(); 
}
Weather Station Example 
public class CurrentConditionsDisplay implements Observer, 
DisplayElement 
{ 
private float temperature, humidity; 
private Subject weatherData; 
public CurrentConditionsDisplay(Subject weatherData) { 
this.weatherData = weatherData; 
weatherData.registerObserver(this); 
} 
public void update(float temp, float humidity, float pressure) { 
this.temperature = temp; 
this.humidity = humidity; 
display(); 
} 
public void display() { 
System.out.println("Current conditions: " + temperature + "C " + 
"Humidity: " + humidity + "%"); 
} 
} 
Registering 
this as an 
observer 
The subject 
will call 
update
Weather Station Example 
public class WeatherStation 
{ 
public static void main(String[] args) 
{ 
WeatherData weatherData = new WeatherData(); 
CurrentConditionsDisplay currentDisplay = new 
CurrentConditionsDisplay(weatherData); 
weatherData.setMeasurement(15, 50, 30); 
} 
} 
Current conditions: 15.0C Humidity: 50.0%
Loose Coupling 
 When two object are loosley coupled, the can 
interact but they have very little knowledge of each 
other 
 The Observer Pattern loosley coupled design 
– The only thing the subject knows about observer is that it 
implements a ceratain interface 
– We can add new observers at any time 
– We never need to modify the subject to add new types of 
observers 
– We can reuse subjects or observers independent of each 
other
Loosley Coupled Principle 
Strive for loosely coupled 
designs between objects 
that interact
The Open-Closed Principle
The Open-Closed Principle 
Software entities like 
classes, modules and 
functions should be open for 
extension but closed for 
modifications
The Open-Closed Principle 
 Design and write code in a fashion that adding 
new functionality would involve minimal changes 
to existing code 
– Most changes will be handled as new methods and 
new classes 
– Designs following this principle would result in 
resilient code which does not break on addition of 
new functionality
Resource Allocator Example 
public class ResourceAllocator 
{ 
... 
public int allocate(intresourceType) 
{ 
intresourceId; 
switch (resourceType) 
{ 
case TIME_SLOT: 
resourceId = findFreeTimeSlot(); 
markTimeslotBusy(resourceId); 
break; 
case SPACE_SLOT: 
resourceId = findFreeSpaceSlot(); 
markSpaceSlotBusy(resourceId); 
break; 
... 
} 
return resourceId; 
} 
... 
Holy Buckets!! 
I need to change 
the class for new 
types!!! Horrible!
Resource Allocator Example 
 Design for extensions 
List resources = new ArrayList(); 
... 
public int allocate(intresourceType) 
{ 
int resourceId = findFreeResource(resourceType); 
markAsBusy(resourceId); 
return resourceId; 
}
Another Example 
protected String normalize(char cCharacter) 
{ 
switch(cCharacter) { 
case '<': return "&lt;"; 
case '>': return "&gt;"; 
case '&’: return "&amp;"; 
case '"’: return "&quot;"; 
default: return ""+cCharacter; 
} } 
What is wrong with 
this code? 
 This is not complete 
 This is common problem – a library must exists 
 If making it yourself, a Map would be better
Callback Handlers
Task 
We need to create program that reads feeds 
Feed can be RSS news, XML or what ever 
The program must be loosely coupled 
New feed types will come
Creating Objects 
 Where does the creation take place? 
Enterprise Application 
This stays the same 
This that is added
Call-back Handlers 
 Inverting the Dependency 
– Let a class call you back 
ReaderProcess RssFeedReader 
processEntry 
processEntry 
processEntry 
 Example 
– sort routine, reading records 
Read
Example: Reading RSS 
 Process to read an RSS feed 
– The FeedReader define the role of such readers 
– Concrete readers must implement read and accept a 
call-back handler to get the results back 
public interface FeedReader 
{ 
public boolean read(); 
public void setFeedHandler(FeedHandler handler); 
} 
public interface FeedHandler 
{ 
public void processEntry(FeedEntry entry); 
}
Example: Reading RSS 
 AbstractFeedReader acts as a superclass for 
concrete reader classes 
– Layered Supertype pattern 
public abstract class AbstractFeedReader implements FeedReader 
{ 
protected FeedHandler feedHandler; 
public void setFeedHandler(FeedHandler handler) 
{ 
this.feedHandler = handler; 
} 
public abstract boolean read(); 
}
Example: Reading RSS 
 RssFeedReader 
public class RssFeedReader extends AbstractFeedReader 
{ 
private String source; 
public RssFeedReader(String source) 
{ 
this.source = source; 
} 
public boolean read() 
{ 
// reading ... 
feedHandler.processEntry(new FeedEntry(ent.getTitle(), 
ent.getLink(), ent.getPublishedDate().toString())); 
} 
return true; 
} 
}
Example: Reading RSS 
 ReaderProcess is the client 
public class ReaderProcess implements FeedHandler 
{ 
FeedReader reader; 
public ReaderProcess() 
{ 
ReaderFactory factory = ReaderFactory.getReaderFactory(); 
reader = factory.getFeedReader("http://..."); 
reader.setFeedHandler(this); 
} 
public void processEntry(FeedEntry entry) 
{ 
... 
} 
}
Example: Reading RSS
Call-back Handlers 
 Inverting the Dependency 
– Let a class call you back 
ReaderProcess RssFeedReader 
processEntry 
processEntry 
processEntry 
 Example 
– sort routine, reading records 
Read
Factory
The Problem with “new” 
 new is used to create object 
 Problem is this: 
– Even if we use supertypes (interfaces or abstract 
classes) we have to have concrete class behind it 
Animal animal = new Dog(); 
animal.makeSound(); 
– This violates the Program to Interfaces Design 
Principle 
– The code also violates the Open Closed Principle
Program to an interfaces 
 Dependency Injection 
– Make the caller responsible for setting the dependency 
private Animal animal; 
public setAnimal(Animal animal) 
{ 
this.animal = animal; 
} 
... 
animal.makeSound(); 
Injection happens 
here, in the 
set-method 
LOOSE COUPLING = BEAUTIFUL!
Program to unknown creation 
 What does this mean? 
Animal animal = getAnimal(); 
animal.makeSound(); 
Where is this 
getAnimal 
coming from?
FeedReader 
 Objects are created with new 
public class ReaderProcess 
{ 
FeedReader reader; 
public ReaderProcess() 
{ 
reader = new RssFeedReader 
("http://www.mbl.is/mm/rss/togt.xml"); 
} 
Holy Cow! 
new creates 
concrete object 
not abstraction!!
FeedReader 
 We need to have diffrent types 
public ReaderProcess(String type, String source) 
{ 
if(type.equals("rss")) 
reader = new RssFeedReader(source); 
else if (type.equals("atom")) 
reader = new AtomFeedReader(source); 
else if (type.equals("xml")) 
reader = new XmlFeedReader(source); 
reader.setFeedHandler(this); 
} 
Holy Macaroni! 
This smells!!! 
Violates the OCP
Moving the Dependency 
 The name of the class is put in to a properties 
file 
– ReaderFactory has no clue of what class it is 
pu–bliIct sjutastitc hFeaesdR etaode rbege taFe esdRueabdcerl(a)ss of FeedReader 
{ 
FeedProperties prop = new FeedProperties(); 
Class instanceClass; 
FeedReader reader = null; 
try { 
instanceClass = Class.forName(prop.getProperty("reader")); 
reader = (FeedReader)instanceClass.newInstance(); 
} 
catch (Exception e) { 
System.out.println("loading class failed"); 
return null; 
} 
reader.setSource(prop.getSource()); 
return reader; 
} 
Plugin pattern
Loading Properties 
 Properties class 
public class FeedProperties extends Properties 
{ 
protected String reader; 
protected String source; 
protected String DEFAULT_PROPERTIES = "feeds.properties"; 
public FeedProperties() 
{ 
try { 
load(new FileInputStream(new File(DEFAULT_PROPERTIES))); 
reader = getProperty("reader"); 
source = getProperty("source"); 
} 
catch (Exception e) { 
System.out.println("Loading properties failed"); 
} 
} 
feeds.properties 
reader=is.ru.honn.feeds.rss.RssFeedReader 
source=http://www.mbl.is/mm/rss/togt.xml
Base Patterns
Base Patterns 
 Gateway 
 Mapper 
 Layer Supertype 
 Separated Interface 
 Registry 
 Value Object 
 Plugin 
 Service Stub
 Fowler’s Catalog 
http://martinfowler.com/eaaCatalog/
Gateway (466) 
An object that encapsulates access to an external 
system or resource 
 Wrap external APIs into an interface 
– API is usually for accessing some external resource 
• Examples: JDBC, JDom, financial software
Gateway (466) 
 How It Works 
– Create a simple API and use it access the external 
API through a Gateway 
– All access is easily defined 
– Change in the resource does not require changes in 
the client software 
– Gateways should be simple – complex logic should 
not be in the clients of the Gateway 
– Gateways can be generated
Gateway (466) 
 When to Use It 
– Gateway is useful when accessing external service 
– Can be applied with Service Stub (504) 
– Clear benefit is that is makes it easy to swap out one 
kind of resource for another
Mapper (473) 
An object that sets up communiction between 
two independent objects 
 Create communication between two systems but 
you still need to make them independent
Mapper (473) 
 How it Works 
– A Mapper is an insulating layer between subsystems 
– It controls the details of communication between them 
without either subsystem being aware of it 
– Mappers are fairly easy as they are well-defined 
– The tricky part is what system invokes them – third 
party system or make the Mapper an Observer 
 When to Use it 
– When you want to decouple different parts of a 
system
Layer Supertype (475) 
A type that acts as the supertype 
for all types in its layer 
 Super class that contains common functionality 
in a layer 
 How it works 
– Use this pattern when you 
have common features 
from all objects in a layer
Layer Supertype (475) 
 When to use it 
– When you have common features from all objects in a 
layer. 
 Example 
– Domain objects can 
have a common 
superclass for 
ID handling 
class DomainObject... 
private Long ID; 
public Long getID() 
{ 
return ID; 
} 
public void setID(Long ID) 
{ 
this.ID = ID; 
} 
public DomainObject(Long ID) 
{ 
this.ID = ID; 
}
Example: Drawing system 
 Shape class revisited 
public abstract class Shape implements Drawable 
{ 
protected int x,y; 
} 
– All objects in the drawing layer must have an origin (x 
and y) and implement Drawable
Separated Interface (476) 
Defines an interface in a separate 
package from its implementation 
 Decouples parts of a system 
– Controls the dependencies between packages 
– Implementation can easily be changed 
 How it works 
– Interface and implementation is placed in separate 
packages 
– Client uses the interface 
– Implementation can be determined at configuration 
time
Separated Interface 
 Layered System 
– Domain layer depends on Data Source layer 
– Data Source layer cannot access Domain layer 
Domain Layer 
Data Source Layer 
JDBC 
Code 
Concreate class 
RowCallBackHandler 
processRow(ResultSet rs) 
Interface 
RowCallBackHandler 
processRow(ResultSet rs) 
implements 
Code reading SQL 
Execution calls 
Separated interface
Separated Interface (476) 
 Implementation is placed in a separate package 
Developers of the client 
package are responsible for 
the interface
Separated Interface (476)
Separated Interface (476) 
 Instantiating the implementation 
– User of the interface should not know the 
implementation 
 Solutions 
– Use a Factory and Plugin method 
– Use Dependency Injection
Separated Interface (476) 
public interface FeedHandler 
{ 
public void processObject (FeedEntry entry); 
} 
public class ReaderClient implements FeedHandler 
{ 
... 
public ReaderClient() 
{ 
FeedReader reader = ReaderFactory.getFeedReader(); 
reader.setFeedHandler(this); 
reader.read("http://rss.news.yahoo.com/rss/tech"); 
} 
public void processObject(FeedEntry entry) 
{ 
System.out.println(entry); 
} 
} 
Callback
Registry (480) 
A well-known object that other objects can use 
to find common objects and services 
 A registry is a global object 
 How It Works 
– Object that can easily be accessed at any time 
– Only one object available at any time 
– Provides services or information 
– Can have different scopes 
– Usually not mutable data 
– Example: System Settings, Loggers
Singleton Registry (480) 
 Only one instance running 
public class Registry 
{ 
private static Registry soleInstance = new Registry(); 
public static Registry getInstance() 
{ 
return soleInstance; 
 When to Use It 
– As a last resort 
} 
private Registry() 
{ 
} 
... 
} 
Registry registry = Registry.getInstance(); 
//registry = new Registry (); Does not work
Value Object (486) 
A small simple object, like money or date 
range, whose equality isn’t based on identity 
 Small and easily created objects that hold and 
represent some data 
 How it works 
– Not based on identity 
– Equality is based on comparing values of the object 
– Can be immutable (example is the Date class) 
 When to use it 
– When you’re basing equality on something other than 
identify
Value Object (486) 
 Examples 
– Date, Money 
class Money... 
private long amount; 
private Currency currency; 
public Money(double amount, Currency currency) 
{ 
this.currency = currency; 
this.amount = Math.round(amount * centFactor()); 
} 
...
Value Object Example: Date 
GregorianCalendar cal = new GregorianCalendar(); 
cal.set(1865, Calendar.APRIL, 14); 
Date d1 = cal.getTime(); 
cal.set(1963, Calendar.NOVEMBER, 22); 
Date d2 = cal.getTime(); 
System.out.println(d1.equals(d2)); 
cal.set(1756, Calendar.JANUARY, 27); 
Date d3 = cal.getTime(); 
Date d4 = cal.getTime(); 
System.out.println(d3.equals(d4)); 
false 
true
Plugin (499) 
Links classes during configuration 
rather than compilation 
 Use plugin to provide specific implantation 
– Plugins implement specific interface use by the client 
application code 
– Decision at configuration time or run time 
– Use factory to load in the plugin 
– For example: on plugin for test, another for production
Plugin (499) 
 A caller obtains a Plugin implementation of a 
caller a plugin factory a plugin configuration 
getPlugin 
lookupPluginByType 
new 
a plugin 
separated interface 
 When to Use It 
– Use plugin when you have behavior that requires 
different implementations based on runtime 
environment
Plugin (499) 
 ReaderClient uses ReaderFactory to get an 
interface to FeedReader 
ReaderClient ReaderFactory reader.properties 
getFeedReader 
props.getProperty("reader") 
 reader.properties define the name of the actual 
implementation class 
new 
FeedReader
Plugin (499) 
public ReaderClient() 
{ 
FeedReader reader = ReaderFactory.getFeedReader(); 
... 
} public class ReaderFactory 
{ 
public static FeedReader getFeedReader() 
{ 
... 
try 
{ 
props.load(new FileInputStream(new File("reader.properties"))); 
instanceClass = Class.forName(props.getProperty("reader")); 
reader = (FeedReader)instanceClass.newInstance(); 
} ... 
return reader; 
} 
} reader=RssFeedReader
Service Stub (504) 
Removes dependence upon problematic 
services during testing 
 Enterprise systems often need to access 
external system 
– Can be out of developers control
Service Stub (504) 
 Service stub provides implementation for 
development and testing purposes 
– Runs locally and in-memory 
– Implements the same interface of the gateway used 
to access the real service 
 When to Use It 
– Service stub is useful when dependence on a 
particular service is hindering development or testing 
– Called “Mock Object” in the extreme programming 
world
Service Stub Examples 
public class ReaderStub extends AbstractFeedReader 
{ 
public void read(String url) 
{ 
feedHandler.processEntry(new FeedEntry("title1", "Bla bla bla")); 
feedHandler.processEntry(new FeedEntry("title2", "Bla bla bla")); 
feedHandler.processEntry(new FeedEntry("title3", "Bla bla bla")); 
} 
} 
title1 
Bla bla bla 
title2 
Bla bla bla 
title3 
Bla bla bla 
reader.properties 
reader=ReaderStub
Summary 
 Base Patterns 
– Gateway, Mapper, Layerd Supertype, Separated 
Interface, Registry, Value Object, Plugin, Service 
Stub, Record Set 
 Next: From Problem to Patterns 
– Using design patterns
QUIZ
Question #1 
 You use this patterns when you need to break 
a dependency between two parts of the 
system 
A) Registry 
B) Gateway 
C) Separated Interface 
D) Plugin
Question #2 
 Intent of a pattern is this: An object that sets 
up communication between two objects 
A) Gateway 
B) Mapper 
C) Registry 
D) Value Object
Question #3 
 Sketch of a pattern is his 
A) Plugin 
B) Mapper 
C) Registry 
D) Service Stub
Question #4 
 Use this pattern when you find that dependence 
on a particular service is hindering your 
development and testing 
A) Mapper 
B) Record Set 
C) Service Stub 
D) Gateway
Next 
 Using Design Patterns

More Related Content

What's hot

[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineering[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineeringIvano Malavolta
 
PATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternPATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternMichael Heron
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanPriyanka Pradhan
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patternsAmit Kabra
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software EngineeringManish Kumar
 
Design pattern
Design patternDesign pattern
Design patternOmar Isaid
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1Shahzad
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
UNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOP
UNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOPUNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOP
UNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOPAmit Midha
 

What's hot (20)

[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineering[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineering
 
Design pattern
Design patternDesign pattern
Design pattern
 
PATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternPATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design Pattern
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software Engineering
 
Design pattern
Design patternDesign pattern
Design pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
09 grasp
09 grasp09 grasp
09 grasp
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Unit 3
Unit 3Unit 3
Unit 3
 
UNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOP
UNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOPUNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOP
UNDERSTANDING OOAD AND DESIGN PATTERNS USING UML AND JAVA-TRAINING WORKSHOP
 

Similar to L05 Design Patterns

12266422.ppt
12266422.ppt12266422.ppt
12266422.pptCSEC5
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2Ankit Dubey
 
Writting Better Software
Writting Better SoftwareWritting Better Software
Writting Better Softwaresvilen.ivanov
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxDrYogeshDeshmukh1
 
Object Oriented Analysis
Object Oriented AnalysisObject Oriented Analysis
Object Oriented AnalysisAMITJain879
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataCory Foy
 
Design patterns for fun & profit - CoderCruise 2018
Design patterns for fun & profit - CoderCruise 2018Design patterns for fun & profit - CoderCruise 2018
Design patterns for fun & profit - CoderCruise 2018David Litvak Bruno
 
Cs690 object oriented_software_engineering_team01_ report
Cs690 object oriented_software_engineering_team01_ reportCs690 object oriented_software_engineering_team01_ report
Cs690 object oriented_software_engineering_team01_ reportKhushboo Wadhwani
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility PrincipleBADR
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
session on pattern oriented software architecture
session on pattern oriented software architecturesession on pattern oriented software architecture
session on pattern oriented software architectureSUJOY SETT
 
Design Patterns Explained: From Analysis through Implementation
Design Patterns Explained: From Analysis through ImplementationDesign Patterns Explained: From Analysis through Implementation
Design Patterns Explained: From Analysis through ImplementationTechWell
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallJohn Mulhall
 

Similar to L05 Design Patterns (20)

L03 Design Patterns
L03 Design PatternsL03 Design Patterns
L03 Design Patterns
 
Design Patterns.ppt
Design Patterns.pptDesign Patterns.ppt
Design Patterns.ppt
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2
 
Writting Better Software
Writting Better SoftwareWritting Better Software
Writting Better Software
 
010821+presentation+oti.ppt
010821+presentation+oti.ppt010821+presentation+oti.ppt
010821+presentation+oti.ppt
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptx
 
Object Oriented Analysis
Object Oriented AnalysisObject Oriented Analysis
Object Oriented Analysis
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and Data
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Design patterns for fun & profit - CoderCruise 2018
Design patterns for fun & profit - CoderCruise 2018Design patterns for fun & profit - CoderCruise 2018
Design patterns for fun & profit - CoderCruise 2018
 
Cs690 object oriented_software_engineering_team01_ report
Cs690 object oriented_software_engineering_team01_ reportCs690 object oriented_software_engineering_team01_ report
Cs690 object oriented_software_engineering_team01_ report
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
session on pattern oriented software architecture
session on pattern oriented software architecturesession on pattern oriented software architecture
session on pattern oriented software architecture
 
Design Patterns Explained: From Analysis through Implementation
Design Patterns Explained: From Analysis through ImplementationDesign Patterns Explained: From Analysis through Implementation
Design Patterns Explained: From Analysis through Implementation
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John Mulhall
 
L06 Using Design Patterns
L06 Using Design PatternsL06 Using Design Patterns
L06 Using Design Patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

More from Ólafur Andri Ragnarsson

New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionÓlafur Andri Ragnarsson
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine Ólafur Andri Ragnarsson
 

More from Ólafur Andri Ragnarsson (20)

Nýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfaraNýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfara
 
Nýjast tækni og framtíðin
Nýjast tækni og framtíðinNýjast tækni og framtíðin
Nýjast tækni og framtíðin
 
New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course Introduction
 
L01 Introduction
L01 IntroductionL01 Introduction
L01 Introduction
 
L23 Robotics and Drones
L23 Robotics and Drones L23 Robotics and Drones
L23 Robotics and Drones
 
L22 Augmented and Virtual Reality
L22 Augmented and Virtual RealityL22 Augmented and Virtual Reality
L22 Augmented and Virtual Reality
 
L20 Personalised World
L20 Personalised WorldL20 Personalised World
L20 Personalised World
 
L19 Network Platforms
L19 Network PlatformsL19 Network Platforms
L19 Network Platforms
 
L18 Big Data and Analytics
L18 Big Data and AnalyticsL18 Big Data and Analytics
L18 Big Data and Analytics
 
L17 Algorithms and AI
L17 Algorithms and AIL17 Algorithms and AI
L17 Algorithms and AI
 
L16 Internet of Things
L16 Internet of ThingsL16 Internet of Things
L16 Internet of Things
 
L14 From the Internet to Blockchain
L14 From the Internet to BlockchainL14 From the Internet to Blockchain
L14 From the Internet to Blockchain
 
L14 The Mobile Revolution
L14 The Mobile RevolutionL14 The Mobile Revolution
L14 The Mobile Revolution
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine
 
L12 digital transformation
L12 digital transformationL12 digital transformation
L12 digital transformation
 
L10 The Innovator's Dilemma
L10 The Innovator's DilemmaL10 The Innovator's Dilemma
L10 The Innovator's Dilemma
 
L09 Disruptive Technology
L09 Disruptive TechnologyL09 Disruptive Technology
L09 Disruptive Technology
 
L09 Technological Revolutions
L09 Technological RevolutionsL09 Technological Revolutions
L09 Technological Revolutions
 
L07 Becoming Invisible
L07 Becoming InvisibleL07 Becoming Invisible
L07 Becoming Invisible
 
L06 Diffusion of Innovation
L06 Diffusion of InnovationL06 Diffusion of Innovation
L06 Diffusion of Innovation
 

Recently uploaded

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 

Recently uploaded (20)

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 

L05 Design Patterns

  • 1. Lecture 05 Design Patterns
  • 2. Agenda  Patterns – History, classification, structure  Design Principles – Loosley Coupled Design Principle – Open-Close Principle  Base Patterns
  • 3. Reading  Design Patterns  Observer pattern  Factory pattern  Base Patterns  The Open-Closed Principle
  • 5. Design Patterns  Design pattern is a general solution to a common problem in software design – Systematic approach for problems that reoccur in software development – Not complete solution but starting point for design – Not code ready to use – Patterns have names and definitions – Built on common practices  Patterns should not be language dependant – However patterns apply for types of programming languages
  • 6. History  Patterns originated as an architectural concept “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice” - Christopher Alexander
  • 7. History  Landmark book from 1995:Design Patterns: Elements of Reusable Object-Oriented Software – Gang of Four (GoF) – Term Design Pattern is borrowed from the construction industry  Several books on patterns have been published since – Head First Design Patterns for example
  • 8. Vintage Design Patterns  Design Patterns are like good red wine – You cannot appreciate them at first – As you study them you learn the difference between plonk and vintage, or bad and good designs – As you become a connoisseur you experience the various textures you didn’t notice before  Warning: – Once you are hooked, you will no longer be satisfied with inferior designs Dr. Heinz Kabutz (http://www.javaspecialists.co.za)
  • 9. Pattern Classification  Design patterns can be classified based on multiple criteria – Basic underlying problem they solve  Classification – Fundamental patterns – Creational patterns – Structural patterns – Behavioral patterns – Concurrency patterns
  • 10. Enterprise Patterns Classification  Domain Logic Patterns  Data Source Architectural Patterns  Object-Relational Behavioral Patterns  Object-Relational Structural Patterns  Object-Relational Metadata Mapping Patterns  Web Presentation Patterns  Distribution Patterns  Offline Concurrency Patterns  Session State Patterns  Base Patterns
  • 11. QUIZ Which of these statements is not true A) Design Patterns are based on solutions from practice B) Design Patterns are ideas not code C) Design Patterns are based on specific programming languages D) Design Patterns can have ambiguous names
  • 12. QUIZ Which of these statements is not true A) Design Patterns are based on solutions from practice B) Design Patterns are ideas not code C) Design Patterns are based on specific programming languages D) Design Patterns can have ambiguous names ✔
  • 14. Structure of Patterns  Name  The Intent  The Sketch  Motivation  How it Works  When to Use it  Further Reading  Examples
  • 15. The Name  Pattern names are important – Need to create a vocabulary – Need to describe the pattern well – Avoid ambiguity and misunderstanding  Problems with names – Authors are using different names for same pattern • Data Access Object and Table Data Gateway • Dependency Injection and Inversion of Control – Authors are using same name for different patterns • Example: Value Object is used for two similar patterns
  • 16. The Intent  Sums up the pattern in a sentence or two – Value Object: A small simple object, like money or date range, whose equality isn’t based on identity
  • 17. The Sketch  Visual representation of the pattern, often but not always a UML diagram
  • 18. Motivation  Description of a motivating problem for the pattern – Problem description – May not be the only problem for the pattern  Example: – Layered supertype It’s not uncommon for all the objects in a layer to have methods you don’t want to have duplicated throughout the system. You can move this behavior into a common Layer Supertype
  • 19. How it Works  Describes the solution – Implementation Issues – Variations – Independent of any particular platform – Platform dependent sections are identified – UML Diagrams if applicable  Plugin example
  • 20. When to Use It  Describes when the pattern should be used – Trade-offs – Comparisons  Layered Supertype example – Use Layer Supertype when you have common features from all objects in a layer
  • 21. Examples  Example code in Java or C# – Layer Supertype  Not working code – pseudo code to give idea class DomainObject... private Long ID; public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; } public DomainObject(Long ID) { this.ID = ID; }
  • 22. Using Design Patterns  How to use design patterns? – Problem is the patterns can be complex and detailed – Usually they are generic and abstract  Ways to study patterns – Implement them in test code – Sketch a class diagram in your context to see the class dependencies – Form a “Study group” to discuss the patterns – Learn the vocabulary – Practice, practice, practice
  • 23. Problems with Patterns  Ambiguity in Vocabulary – Same pattern has different names – Different Patterns have same name  Appling the wrong pattern – Over-designing the solution – Patterns design for one language might not be needed in another  Not solving the original problem – Using Remote Façade instead of avoiding network latencies – Using EJB Entity Beans
  • 24. EXERCISE Job interview question You are given the assignment of creating a component that needs to know sales statistics of Lottery tickets. You know that there is a another component in the system, Sale Server, that handles the sale. You need real-time information. What would you suggest?
  • 25. First proposal: Sale Server will call Bingo Sale server Bingo Problem is that the Sale Server developer refuses to make a call to a specific game. His argument is that Sale Server should be for sale, and not be cluttered with game specific code. Another solution is needed.
  • 26.
  • 29. The Weather Monitoring Example  The Weather Monitoring application
  • 30. The Weather Monitoring Example  Task – We need to implement measurementsChanged so that it updates three different displays for current conditions, weather stats, and forcasts – measurementsChanged is called any time data changes, we don’t know or care how this method is called – Three display types must be updated – The system must be expandable – new display types will be added
  • 31. The Weather Monitoring Example  WeatherData class public class WeatherData { // instance variable declarations public void measurementsChanged() { float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure(); currentConditionsDisplay.update (temp, humidity, pressure); statisticsDisplay.update (temp, humidity, pressure); forcastConditionsDisplay.update (temp, humidity, pressure); } ... }
  • 32. QUIZ  Based on our first implementation, which of the following apply A. We are coding to concrete implementation not abstractions B. For every new display element we need to alter code C. We have no way to add (or remove) display elements at runtime D. The display elements don’t implement a common interface E. We have not encapsulated the part that changes F. We are violating encapsulation of the WeatherData class
  • 33. The Weather Monitoring Example  WeatherData class public class WeatherData { // instance variable declarations public void measurementsChanged() { float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure(); Interface is that same for all currentConditionsDisplay.update (temp, humidity, pressure); statisticsDisplay.update (temp, humidity, pressure); forcastConditionsDisplay.update (temp, humidity, pressure); } ... } By coding to concreate implementation we have no way to add or remove displays without code change
  • 34. Observer One or more observers or listeners are registered to observe an event which may be raised by the observed object (the subject)  Sometimes called publish/subscribe – Similar to call-back handlers – One-to-Many relationship  Benefits – Listening object gets information when needed – Subject does not become dependent on multiple observers
  • 36. Observer Design Pattern  Subject does not depend on listeners
  • 37. Loose Coupling  When two object are loosley coupled, the can interact but they have very little knowledge of each other  The Observer Pattern loosley coupled design – The only thing the subject knows about observer is that it implements a ceratain interface – We can add new observers at any time – We never need to modify the subject to add new types of observers – We can reuse subjects or observers independent of each other
  • 38. Loosley Coupled Principle Strive for loosely coupled designs between objects that interact
  • 39. Weather Station Example public interface Subject { public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObservers(); } public interface Observer { public void update(float temp, float humidity, float pressure); public interface DisplayElement { public void display(); } }
  • 40. Weather Station Example public class WeatherData implements Subject { private ArrayList observers; private float temperature, humidity, pressure; public WeatherData() { observers = new ArrayList(); } public void registerObserver(Observer o) { observers.add(o); } public void removeObserver(Observer o) { int i = observers.indexOf(o); if (i>= 0) observers.remove(i); }
  • 41. Weather Station Example public void notifyObservers() { for (int i = 0; i<observers.size(); i++) { Observer observer = (Observer)observers.get(i); observer.update(temperature, humidity, pressure); } } public void measurementsChanged() { notifyObservers(); } // Test code public void setMeasurement(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; this.measurementsChanged(); }
  • 42. Weather Station Example public class CurrentConditionsDisplay implements Observer, DisplayElement { private float temperature, humidity; private Subject weatherData; public CurrentConditionsDisplay(Subject weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); } public void update(float temp, float humidity, float pressure) { this.temperature = temp; this.humidity = humidity; display(); } public void display() { System.out.println("Current conditions: " + temperature + "C " + "Humidity: " + humidity + "%"); } } Registering this as an observer The subject will call update
  • 43. Weather Station Example public class WeatherStation { public static void main(String[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); weatherData.setMeasurement(15, 50, 30); } } Current conditions: 15.0C Humidity: 50.0%
  • 44. Loose Coupling  When two object are loosley coupled, the can interact but they have very little knowledge of each other  The Observer Pattern loosley coupled design – The only thing the subject knows about observer is that it implements a ceratain interface – We can add new observers at any time – We never need to modify the subject to add new types of observers – We can reuse subjects or observers independent of each other
  • 45. Loosley Coupled Principle Strive for loosely coupled designs between objects that interact
  • 47. The Open-Closed Principle Software entities like classes, modules and functions should be open for extension but closed for modifications
  • 48. The Open-Closed Principle  Design and write code in a fashion that adding new functionality would involve minimal changes to existing code – Most changes will be handled as new methods and new classes – Designs following this principle would result in resilient code which does not break on addition of new functionality
  • 49. Resource Allocator Example public class ResourceAllocator { ... public int allocate(intresourceType) { intresourceId; switch (resourceType) { case TIME_SLOT: resourceId = findFreeTimeSlot(); markTimeslotBusy(resourceId); break; case SPACE_SLOT: resourceId = findFreeSpaceSlot(); markSpaceSlotBusy(resourceId); break; ... } return resourceId; } ... Holy Buckets!! I need to change the class for new types!!! Horrible!
  • 50. Resource Allocator Example  Design for extensions List resources = new ArrayList(); ... public int allocate(intresourceType) { int resourceId = findFreeResource(resourceType); markAsBusy(resourceId); return resourceId; }
  • 51. Another Example protected String normalize(char cCharacter) { switch(cCharacter) { case '<': return "&lt;"; case '>': return "&gt;"; case '&’: return "&amp;"; case '"’: return "&quot;"; default: return ""+cCharacter; } } What is wrong with this code?  This is not complete  This is common problem – a library must exists  If making it yourself, a Map would be better
  • 53. Task We need to create program that reads feeds Feed can be RSS news, XML or what ever The program must be loosely coupled New feed types will come
  • 54. Creating Objects  Where does the creation take place? Enterprise Application This stays the same This that is added
  • 55. Call-back Handlers  Inverting the Dependency – Let a class call you back ReaderProcess RssFeedReader processEntry processEntry processEntry  Example – sort routine, reading records Read
  • 56. Example: Reading RSS  Process to read an RSS feed – The FeedReader define the role of such readers – Concrete readers must implement read and accept a call-back handler to get the results back public interface FeedReader { public boolean read(); public void setFeedHandler(FeedHandler handler); } public interface FeedHandler { public void processEntry(FeedEntry entry); }
  • 57. Example: Reading RSS  AbstractFeedReader acts as a superclass for concrete reader classes – Layered Supertype pattern public abstract class AbstractFeedReader implements FeedReader { protected FeedHandler feedHandler; public void setFeedHandler(FeedHandler handler) { this.feedHandler = handler; } public abstract boolean read(); }
  • 58. Example: Reading RSS  RssFeedReader public class RssFeedReader extends AbstractFeedReader { private String source; public RssFeedReader(String source) { this.source = source; } public boolean read() { // reading ... feedHandler.processEntry(new FeedEntry(ent.getTitle(), ent.getLink(), ent.getPublishedDate().toString())); } return true; } }
  • 59. Example: Reading RSS  ReaderProcess is the client public class ReaderProcess implements FeedHandler { FeedReader reader; public ReaderProcess() { ReaderFactory factory = ReaderFactory.getReaderFactory(); reader = factory.getFeedReader("http://..."); reader.setFeedHandler(this); } public void processEntry(FeedEntry entry) { ... } }
  • 61. Call-back Handlers  Inverting the Dependency – Let a class call you back ReaderProcess RssFeedReader processEntry processEntry processEntry  Example – sort routine, reading records Read
  • 63. The Problem with “new”  new is used to create object  Problem is this: – Even if we use supertypes (interfaces or abstract classes) we have to have concrete class behind it Animal animal = new Dog(); animal.makeSound(); – This violates the Program to Interfaces Design Principle – The code also violates the Open Closed Principle
  • 64. Program to an interfaces  Dependency Injection – Make the caller responsible for setting the dependency private Animal animal; public setAnimal(Animal animal) { this.animal = animal; } ... animal.makeSound(); Injection happens here, in the set-method LOOSE COUPLING = BEAUTIFUL!
  • 65. Program to unknown creation  What does this mean? Animal animal = getAnimal(); animal.makeSound(); Where is this getAnimal coming from?
  • 66. FeedReader  Objects are created with new public class ReaderProcess { FeedReader reader; public ReaderProcess() { reader = new RssFeedReader ("http://www.mbl.is/mm/rss/togt.xml"); } Holy Cow! new creates concrete object not abstraction!!
  • 67. FeedReader  We need to have diffrent types public ReaderProcess(String type, String source) { if(type.equals("rss")) reader = new RssFeedReader(source); else if (type.equals("atom")) reader = new AtomFeedReader(source); else if (type.equals("xml")) reader = new XmlFeedReader(source); reader.setFeedHandler(this); } Holy Macaroni! This smells!!! Violates the OCP
  • 68. Moving the Dependency  The name of the class is put in to a properties file – ReaderFactory has no clue of what class it is pu–bliIct sjutastitc hFeaesdR etaode rbege taFe esdRueabdcerl(a)ss of FeedReader { FeedProperties prop = new FeedProperties(); Class instanceClass; FeedReader reader = null; try { instanceClass = Class.forName(prop.getProperty("reader")); reader = (FeedReader)instanceClass.newInstance(); } catch (Exception e) { System.out.println("loading class failed"); return null; } reader.setSource(prop.getSource()); return reader; } Plugin pattern
  • 69. Loading Properties  Properties class public class FeedProperties extends Properties { protected String reader; protected String source; protected String DEFAULT_PROPERTIES = "feeds.properties"; public FeedProperties() { try { load(new FileInputStream(new File(DEFAULT_PROPERTIES))); reader = getProperty("reader"); source = getProperty("source"); } catch (Exception e) { System.out.println("Loading properties failed"); } } feeds.properties reader=is.ru.honn.feeds.rss.RssFeedReader source=http://www.mbl.is/mm/rss/togt.xml
  • 71. Base Patterns  Gateway  Mapper  Layer Supertype  Separated Interface  Registry  Value Object  Plugin  Service Stub
  • 72.  Fowler’s Catalog http://martinfowler.com/eaaCatalog/
  • 73. Gateway (466) An object that encapsulates access to an external system or resource  Wrap external APIs into an interface – API is usually for accessing some external resource • Examples: JDBC, JDom, financial software
  • 74. Gateway (466)  How It Works – Create a simple API and use it access the external API through a Gateway – All access is easily defined – Change in the resource does not require changes in the client software – Gateways should be simple – complex logic should not be in the clients of the Gateway – Gateways can be generated
  • 75. Gateway (466)  When to Use It – Gateway is useful when accessing external service – Can be applied with Service Stub (504) – Clear benefit is that is makes it easy to swap out one kind of resource for another
  • 76. Mapper (473) An object that sets up communiction between two independent objects  Create communication between two systems but you still need to make them independent
  • 77. Mapper (473)  How it Works – A Mapper is an insulating layer between subsystems – It controls the details of communication between them without either subsystem being aware of it – Mappers are fairly easy as they are well-defined – The tricky part is what system invokes them – third party system or make the Mapper an Observer  When to Use it – When you want to decouple different parts of a system
  • 78. Layer Supertype (475) A type that acts as the supertype for all types in its layer  Super class that contains common functionality in a layer  How it works – Use this pattern when you have common features from all objects in a layer
  • 79. Layer Supertype (475)  When to use it – When you have common features from all objects in a layer.  Example – Domain objects can have a common superclass for ID handling class DomainObject... private Long ID; public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; } public DomainObject(Long ID) { this.ID = ID; }
  • 80. Example: Drawing system  Shape class revisited public abstract class Shape implements Drawable { protected int x,y; } – All objects in the drawing layer must have an origin (x and y) and implement Drawable
  • 81. Separated Interface (476) Defines an interface in a separate package from its implementation  Decouples parts of a system – Controls the dependencies between packages – Implementation can easily be changed  How it works – Interface and implementation is placed in separate packages – Client uses the interface – Implementation can be determined at configuration time
  • 82. Separated Interface  Layered System – Domain layer depends on Data Source layer – Data Source layer cannot access Domain layer Domain Layer Data Source Layer JDBC Code Concreate class RowCallBackHandler processRow(ResultSet rs) Interface RowCallBackHandler processRow(ResultSet rs) implements Code reading SQL Execution calls Separated interface
  • 83. Separated Interface (476)  Implementation is placed in a separate package Developers of the client package are responsible for the interface
  • 85. Separated Interface (476)  Instantiating the implementation – User of the interface should not know the implementation  Solutions – Use a Factory and Plugin method – Use Dependency Injection
  • 86. Separated Interface (476) public interface FeedHandler { public void processObject (FeedEntry entry); } public class ReaderClient implements FeedHandler { ... public ReaderClient() { FeedReader reader = ReaderFactory.getFeedReader(); reader.setFeedHandler(this); reader.read("http://rss.news.yahoo.com/rss/tech"); } public void processObject(FeedEntry entry) { System.out.println(entry); } } Callback
  • 87. Registry (480) A well-known object that other objects can use to find common objects and services  A registry is a global object  How It Works – Object that can easily be accessed at any time – Only one object available at any time – Provides services or information – Can have different scopes – Usually not mutable data – Example: System Settings, Loggers
  • 88. Singleton Registry (480)  Only one instance running public class Registry { private static Registry soleInstance = new Registry(); public static Registry getInstance() { return soleInstance;  When to Use It – As a last resort } private Registry() { } ... } Registry registry = Registry.getInstance(); //registry = new Registry (); Does not work
  • 89. Value Object (486) A small simple object, like money or date range, whose equality isn’t based on identity  Small and easily created objects that hold and represent some data  How it works – Not based on identity – Equality is based on comparing values of the object – Can be immutable (example is the Date class)  When to use it – When you’re basing equality on something other than identify
  • 90. Value Object (486)  Examples – Date, Money class Money... private long amount; private Currency currency; public Money(double amount, Currency currency) { this.currency = currency; this.amount = Math.round(amount * centFactor()); } ...
  • 91. Value Object Example: Date GregorianCalendar cal = new GregorianCalendar(); cal.set(1865, Calendar.APRIL, 14); Date d1 = cal.getTime(); cal.set(1963, Calendar.NOVEMBER, 22); Date d2 = cal.getTime(); System.out.println(d1.equals(d2)); cal.set(1756, Calendar.JANUARY, 27); Date d3 = cal.getTime(); Date d4 = cal.getTime(); System.out.println(d3.equals(d4)); false true
  • 92. Plugin (499) Links classes during configuration rather than compilation  Use plugin to provide specific implantation – Plugins implement specific interface use by the client application code – Decision at configuration time or run time – Use factory to load in the plugin – For example: on plugin for test, another for production
  • 93. Plugin (499)  A caller obtains a Plugin implementation of a caller a plugin factory a plugin configuration getPlugin lookupPluginByType new a plugin separated interface  When to Use It – Use plugin when you have behavior that requires different implementations based on runtime environment
  • 94. Plugin (499)  ReaderClient uses ReaderFactory to get an interface to FeedReader ReaderClient ReaderFactory reader.properties getFeedReader props.getProperty("reader")  reader.properties define the name of the actual implementation class new FeedReader
  • 95. Plugin (499) public ReaderClient() { FeedReader reader = ReaderFactory.getFeedReader(); ... } public class ReaderFactory { public static FeedReader getFeedReader() { ... try { props.load(new FileInputStream(new File("reader.properties"))); instanceClass = Class.forName(props.getProperty("reader")); reader = (FeedReader)instanceClass.newInstance(); } ... return reader; } } reader=RssFeedReader
  • 96. Service Stub (504) Removes dependence upon problematic services during testing  Enterprise systems often need to access external system – Can be out of developers control
  • 97. Service Stub (504)  Service stub provides implementation for development and testing purposes – Runs locally and in-memory – Implements the same interface of the gateway used to access the real service  When to Use It – Service stub is useful when dependence on a particular service is hindering development or testing – Called “Mock Object” in the extreme programming world
  • 98. Service Stub Examples public class ReaderStub extends AbstractFeedReader { public void read(String url) { feedHandler.processEntry(new FeedEntry("title1", "Bla bla bla")); feedHandler.processEntry(new FeedEntry("title2", "Bla bla bla")); feedHandler.processEntry(new FeedEntry("title3", "Bla bla bla")); } } title1 Bla bla bla title2 Bla bla bla title3 Bla bla bla reader.properties reader=ReaderStub
  • 99. Summary  Base Patterns – Gateway, Mapper, Layerd Supertype, Separated Interface, Registry, Value Object, Plugin, Service Stub, Record Set  Next: From Problem to Patterns – Using design patterns
  • 100. QUIZ
  • 101. Question #1  You use this patterns when you need to break a dependency between two parts of the system A) Registry B) Gateway C) Separated Interface D) Plugin
  • 102. Question #2  Intent of a pattern is this: An object that sets up communication between two objects A) Gateway B) Mapper C) Registry D) Value Object
  • 103. Question #3  Sketch of a pattern is his A) Plugin B) Mapper C) Registry D) Service Stub
  • 104. Question #4  Use this pattern when you find that dependence on a particular service is hindering your development and testing A) Mapper B) Record Set C) Service Stub D) Gateway
  • 105. Next  Using Design Patterns