4. “Each pattern describes a problem that
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
(architect)
5. “A Software Design Pattern names,
abstracts, and identifies the key aspects
of a common design structure that
make it useful for creating a reusable
object-oriented design.”
Design Patterns-Elements of Reusable Object-oriented
Software, Gamma et al. (Gang of Four)
6.
7. a set of best practices
a typified solution to a problem in a given
context
a way to facilitate communication
found not invented
9. No direct code reuse
Pattern overload
Experience-based validation
Hard work integrating patterns in the
development process
8
10. name Contributes to the pattern
vocabulary
synopsis Short description of the problem the
pattern will solve.
forces Requirements, considerations, or
necessary conditions
solution The essence of the solution
counter forces Reasons for not using the pattern.
related patterns Possible alternatives in the design.
9
11. GoF Gang of Four
POSA Pattern-Oriented Software Architecture
PoEAA Patterns of Enterprise Application
Architecture
CJP Core J2EE Patterns
ESP Enterprise Solution Patterns using
Microsoft .NET 10
13. Critical functionality
Large quantity of concurrently accessed data
Large number of screens
Integration
Conceptual dissonance
Complex (ilogic) business rules
14. “[Software Architecture is] the
fundamental organization of a system,
embodied in its components, their
relationships to each other and the
environment, and the principles
governing its design and evolution.“
ANSI/IEEE Std 1471-2000, Recommended Practice for
Architectural Description of Software-Intensive Systems
19. How to represent the business entities?
How to persist its state?
How to code the Business logic?
how to guarantee data coherence?
How to handle application distribution?
21. Revenue recognition
Three different products
Word processors, databases, spreadsheets
Different payment rules
WP – all at once (t)
DB – 3 payments: t, t+30, t+60
SS – 3 payments: t, t+60, t+90
(From Martin Fowler’s PoEAA book)
23. «table»
TRevenueRecognitions
+ «Column» ID : int
+ «Column» contractID : int
+ «Column» dateRecognition : date
+ «Column» amount : currency
«table»
«table»
TContracts
TProducts
«table»
+ «Column» ID : int
TCustomers
+ «Column» ID : int
+ «Column» productID : int
+ «Column» type : varchar
+ «Column» ID : int + «Column» customerID : int
+ «Column» name : varchar
+ «Column» name : varchar + «Column» revenue : currency
+ «Column» dateSigned : date
27. How to represent:
One entity, e.g. Customer?
Collections, e.g., List of customers?
Networked/complex objects, e.g., production plan?
Structure and behaviour
Structure + behaviour?
Structure with behaviour?
Behaviour (and attributes)?
Persistence structure ≠ conceptual structure?
30. User defined code with members for the
entity’s attributes
Product
+ Type : int
+ Name : string
+ ID : int
31. Product Contract
Customer
+ Type : int + Revenue : decimal
+ Name : string + DateSigned : DateTime + Name : string
+ ID : int + CustomerID : int + ID : int
+ ProductID : int
+ ID : int
* + RevenueRecognitions
RevenueRecognition
+ DateRecognition : DateTime
+ Amount : decimal
+ ContractID : int
+ ID : int
32. An XML document (or string) representing an
entity’s structure
<product>
<id>123</id>
<name>SuperWriter 7.3</name>
<type>Word Processor</type>
</product>
33. A DataSet (or derived class) to hold tabular
data (eventually directly from a data source)
34. A class implementing the ResultSet interface to
hold tabular data (eventually directly from a data
source)
39. UI
Uses the
platform’s
ResultSet for
sharing entity data
«table module»
beteween layers
BLL
«table data gateway»
DAL
40. Pattern
A single instance that handles the business
logic for all rows in a database table or view
fonte: Patterns of Enterprise Application Architecture
42. Pattern
An object that acts as a Gateway to a
database table. One instance handles all the
rows in the table
Business
entity
fonte: Patterns of Enterprise Application Architecture
49. UI
These classes only
have attributes
(no business logic-
«table module» Entities
related behaviour)
BLL
«table data gateway»
DAL
50. Product Contract
Customer
+ Type : int + Revenue : decimal
+ Name : string + DateSigned : DateTime + Name : string
+ ID : int + CustomerID : int + ID : int
+ ProductID : int
+ ID : int
* + RevenueRecognitions
RevenueRecognition
+ DateRecognition : DateTime
+ Amount : decimal
+ ContractID : int
+ ID : int
58. Pattern
An object model of the domain that
incorporates both behavior and data
fonte: Patterns of Enterprise Application Architecture
59. Pattern
An object that wraps a row in a database
table or view, encapsulates the database
access, and adds domain logic on that data
fonte: Patterns of Enterprise Application Architecture
58
63. Networks of objects
E.g. Invoice heading relates to invoice details
Invoice details refers to Products
Products refers to Suppliers
…
What to do?
Load them all into memory?
How to disallow multiple in-memory copies
62
64. Pattern
An object that doesn't contain all of the data
you need but knows how to get it.
fonte: Patterns of Enterprise Application Architecture
65. Pattern
Ensures that each object gets loaded only once by
keeping every loaded object in a map. Looks up
objects using the map when referring to them
fonte: Patterns of Enterprise Application Architecture
64
69. // Identity Map
public static IDictionary loaded = new Hashtable();
public static Product LoadById(int productID)
{
// check registry – Identity Map
Product p = (Product)loaded[productID];
if (p != null)
return p;
// load
Product aux = new Product();
DataSet ds = ExecuteQuery(quot;SELECT * FROM TProducts WHERE productID=quot; +
productID);
p = new Product(ds.Tables[0].Rows[0]);
// save in registry
loaded[productID] = p;
return p;
}
70. public void Save() {
BeginTransaction();
object[] parms = new object[] {this.ProductID, this.CustomerID,
this.DateSigned, this.Revenue, this.ID};
if (this.ID != 0) {
sqlContract = quot;UPDATE TContracts SET productId=?, customerID=?,
dateSigned=?, revenue=? WHERE contractID=?quot;;
ExecuteTransactedNonQuery(sqlContract, parms);
ExecuteTransactedNonQuery(quot;DELETE FROM TRevenueRecognitions WHERE
contractID=quot; + this.ID);
} else {
sqlContract = quot;INSERT INTO TContracts(productId, customerId,
dateSigned, revenue) VALUES(?, ?, ?, ?)quot;;
this.myID = ExecuteTransactedNonQuery(sqlContract, parms);
}
foreach (RevenueRecognition r in _RevenueRecognitions) {
string sqlRecognition = quot;INSERT INTO
TRevenueRecognitions(contractID, dateRecognition, amount)
VALUES(?, ?, ?)quot;;
object parms[] = new object[] {this.ID, r.DateRecognition,
r.Amount};
ExecuteTransactedNonQuery(sqlRecognition, parms);
}
CommitTransaction();
}
75. Pattern GoF
Problem:
Allow the client the choice of many alternatives,
but each is complex, and you don't want to
include code for all.
Solution:
Make many implementations of the same
interface, and allow the client to select one and
give it back to you.
76. Pattern GoF
Define a family of algorithms, encapsulate each one, and make
them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.
fonte: Design Patterns: Elements of Reusable Object-Oriented Software
79. Pattern
A layer of Mappers that moves data between
objects and a database while keeping them
independent of each other and the mapper
itself
fonte: Patterns of Enterprise Application Architecture
83. protected Contract ApplyMap(DataSet dsCNR)
{
if (dsCNR].Rows.Count < 1)
return null;
Contract c = new Contract();
c.DateSigned = (DateTime)dsCNR.Tables[0].Rows[0][quot;Datesignedquot;];
c.Revenue = (decimal)dsCNR.Tables[0].Rows[0][quot;Revenuequot;];
c.SetID( (int)dsCNR.Tables[0].Rows[0][quot;IDquot;] );
c.SetProduct( (int) dsCNR.Tables[0].Rows[0][quot;ProductIDquot;],
(string) dsCNR.Tables[0].Rows[0][quot;ProdTypequot;] );
c.SetCustomer( (int)dsCNR.Tables[0].Rows[0][quot;CustomerIDquot;] );
foreach (DataRow r in dsCNR.Tables[0].Rows)
{
c.AddRecognition( (DateTime)r[quot;dateRecognitionquot;],
(decimal)r[quot;amountquot;]);
}
return c;
}
84. public class Contract
{
// !!! to be used only by Mapper
internal void SetProduct(int prodID, string prodType)
{
_ProductID = prodID;
SetStrategy(prodType);
}
private void SetStrategy(string prodType)
{
theStrategy = BaseStrategy.CreateStrategy(prodType, this);
}
}
83
85. public abstract class BaseStrategy
{
protected Contract theContract;
public BaseStrategy(Contract c) {
theContract = c;
}
public static IRevenueRecognitionStrategy CreateStrategy(
string prodType, Contract c)
{
switch (prodType) {
case quot;PTquot;: return new Strategies.PTStrategy(c);
break;
case quot;FCquot;: return new Strategies.FCStrategy(c);
break;
case quot;BDquot;: return new Strategies.BDStrategy(c);
break;
default:
throw new ApplicationException(quot;invalid typequot;);
}
return null;
}
}
87. public void CalculateRevenueRecognitions()
{
_RevenueRecognitions.Clear();
theStrategy.CalculateRevenueRecognitions();
}
// !!! to be used by strategies
internal void AddRecognition(DateTime recognitionDate,
decimal amount)
{
_RevenueRecognitions.Add(
new RevenueRecognition(recognitionDate, amount)
);
}
88. public class BDStrategy : BaseStrategy {
public void CalculateRevenueRecognitions() {
decimal[] allocs = Money.Allocate(theContract.Revenue, 3);
theContract.AddRecognition(theContract.DateSigned, allocs[0]);
theContract.AddRecognition(theContract.DateSigned.AddDays(30),
allocs[1]);
theContract.AddRecognition(theContract.DateSigned.AddDays(60),
allocs[2]);
}
}
public class FCStrategy : BaseStrategy {
public void CalculateRevenueRecognitions() {
decimal[] allocs = Money.Allocate(theContract.Revenue, 3);
theContract.AddRecognition(theContract.DateSigned, allocs[0]);
theContract.AddRecognition(theContract.DateSigned.AddDays(60),
allocs[1]);
theContract.AddRecognition(theContract.DateSigned.AddDays(90),
allocs[2]);
}
}
public class PTStrategy : BaseStrategy {
public void CalculateRevenueRecognitions() {
theContract.AddRecognition(theContract.DateSigned,
theContract.Revenue);
}
}
96. Pattern GoF
Problem:
You need a set of related classes but there are
several sets with different implementations
Solution:
Create a service interface, create several
implementations of those services, create a
factory class for each set of implementations,
provide the client with the correct
implementation behind the interface
97. Pattern GoF
Provides an interface for creating families of
related or dependent objects without
specifying their concrete classes.
101. public class PersonDataAccess
{
public PersonDataAccess() { ... }
public bool Insert(object r) { ... }
public bool Delete(object r) { ... }
public bool Update(object r) { ... }
public object Load(object id) { ... }
}
Add logging to this
existing class
102. public class PersonDataAccess
{
public PersonWithLogDataAccess() { ... }
public bool Insert(object r)
{
...
Log.Write(...);
}
public bool Delete(object r)
{ ... }
public bool Update(object r)
What if instead of
{ ... }
logging you
public object Load(object id)
needed billing?
{ ... }
}
103. public class PersonWithLogDataAccess : PersonDataAcess
{
public PersonWithLogDataAccess() { ... }
public bool Insert(object r)
{
base.Insert(r);
logFile.Write(...);
}
public bool Delete(object r)
{ ... }
public bool Update(object r)
What if you
{ ... }
needed logging
public object Load(object id)
and billing?
{ ... }
}
104. Pattern GoF
Problem:
Allow functionally to be layered around an
abstraction, but still dynamically changeable.
Solution:
Combine inheritance and composition. By making
an object that both subclasses from anther class
and holds an instance of the class, can add new
behavior while referring all other behavior to the
original class.
105. Pattern GoF
Attach additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for
extending functionality.
fonte: Design Patterns: Elements of Reusable Object-Oriented Software
106. public interface IDataAccess
{
public bool Insert(object r);
public bool Delete(object r);
public bool Update(object r);
public object Load(object id);
}
107. public class PersonDataAccess : IDataAccess
{
public PersonDataAccess () { ... }
public bool Insert(object r) { ... }
public bool Delete(object r) { ... }
public bool Update(object r) { ... }
public object Load(object id) { ... }
}
108. public class LoggingDecorator : IDataAccess
{
IDataAccess component;
public LoggingDecorator(IDataAccess component) {
this.component = component;
}
public bool Insert(object r) {
WriteLog(quot;Insertquot;, r);
return component.Insert(r);
}
public bool Delete(object r) { ... }
public bool Update(object r) { ... }
public object Load(object id) { ... }
private void WriteLog(string op, object parms)
{ ... }
}
109. public class TesteDecorator
{
public void Teste()
{
IDataAccess da = new PersonIDataAccess ();
IDataAccess dec = new LoggingDecorator(da);
...
dec.Insert(...);
...
}
}
110. Since the Decorator class implements the
same interface of the Component, it can be
used anywhere you would use a Component
Inheritance wouldn’t allow scenarios with
only Logging or only billing or both
But you can chain Decorators!
111. public class CounterDecorator : IDataAccess
{
int nAcessos = 0;
IDataAccess component;
public CounterDecorator(IDataAccess component) {
this.component = component;
}
public bool Insert(object r) {
nAcessos++;
return component.Insert(r);
}
public bool Delete(object r) { ... }
public bool Update(object r) { ... }
public object Load(object id) { ... }
public int NumOfAccesses { get { return nAcessos; } }
}
112. public class BillingDAL
{
public void Teste()
{
IDataAccess da = new PersonDataAccess();
IDataAccess dec = new LoggingDecorator(da);
IDataAccess cd = new CounterDecorator(dec);
...
cd.Insert(...);
...
CounterDecorator bil = (CounterDecorator)cd;
float custo = bil.NumOfAccesses * PRICE_PER_OP;
...
}
}
119. A combination of a Factory, a
Singleton and a Façade
The desired implementation is loaded
into memory and an instance of the
specific façade is created (reflection)
and returned to the GUI
The UI layer will then interact with the
business layer via the
IRevenueRecognition business
interface ignoring the actual
implementation
120. Each implementation shows a combination of
patterns that form an architectural style
Table module + table data gateway
Domain model / active record These are the
Domain model + data mapper classes the students
must “look”
…
Define the business classes and data access
classes necessary to support the application
requirements defined by the business interface
121. Transaction Script using DataSet
Transaction Script
Transaction Script + Data Gateway
Transaction Script using Custom Classes
Transaction Script
Transaction Script + Row Data Gateway
Table Module
Table Module + Table Data Gateway (DataSet)
Table Module + Table Data Gateway (Custom Classes)
Domain Model
Domain Model + Active Record
Domain Model + Data Mapper
124. Pattern
An object that encapsulate the code that implements the
consumer portion of a contract. They act as proxies to other
services, encapsulating the details of connecting to the
source and performing any necessary translation.
fonte: Enterprise Solution Patterns Using .NET
125. Pattern
Hides the details of accessing the service (ex.,
network protocol)
May be considered a data access component
Native support from most tools (e.g., Visual
Studio, Netbeans, Rational software
Architect) by web service proxies
126. Pattern
Provides a coarse-grained façade on fine-
grained objects to improve efficiency over a
network
fonte: Patterns of Enterprise Application Architecture
127. Pattern
Domain object interfaces are tipically fine grained
Inadequeate for remote operations
Create a surronding layer above domain objects
Local clients use the local interface
The facade may encapsulate the interface of one or
more business objects
Domain objects:
Address.New
Address.Set
Person.AddAddress
Person.Update
Remote Facade:
AddressFacade.AddNewAddressToPerson
128. Pattern
An object that carries data between
processes in order to reduce the number of
method calls.
fonte: Patterns of Enterprise Application Architecture
129. Pattern
Since XML is the de facto standard DTO should
support serialization to/from XML
Should be independent of the underlying domain
object
Should be implemented in accordance with the
requiremnts of the remote application
CompleteCustomerInfoDTO
BasicCustomerInfoDTO
Should be independent of the underlying platform
(e.g., programming language)
DataSet/DataTable .net
ResultSet JDBC
DateTime .net
130. Pattern
Defines an application's boundary with a layer of services
that establishes a set of available operations and coordinates
the application's response in each operation
fonte: Patterns of Enterprise Application Architecture
131. Pattern
Domain logic pattern in the context of service
orientation
May be implemented as a Remote Facade or
may be called by a Remote Facade
134. How to represent the business entities?
How to persist its state?
How to code the Business logic?
How to guarantee data coherence?
How to handle application distribution?
135. Simple to complex logic and good platform
support for Result Sets
Table Module
Complex logic
Domain Model
134
136. Table Module
Table Data Gateway
Domain Model very similar to DB schema
Active Record
Complex Domain Model
Data Mapper
137. Guarantee that in-memory data is only updated
in one place
Identity Map
Mantain a relation between in-memory objects
and database records
Identity field
Avoid loading the entire DB to memory
Lazy Load
136
139. Only in data access layer
Don’t forget Views
Balance dynamic SQL and stored procedures
Flexibility
Security
Easyest implementation for some business
logic (e.g., group operations)
138
140. Use parameters instead of string concatenation
DELETE is uncommon
INSERT causes no locking problem
Must be careful on UPDATE
Concurrent access
Incremental update
E.g. Update quantity on hand
UPDATE Products SET QtyOnHand = 10
UPDATE Products SET QtyOnHand = QtyOnHand + 2
141. Good scalability and user-centered
availability
Optimistic Lock
User cannot loose changes
Pessimistic Lock
142. How to pass objects in a remote call?
Data Transfer Object
How to remotely use objects with “fine grained”
interface?
Remote Façade
How to define a coherent set of operations?
Service Layer / Service Interface
How to hide the implementation details of the remote
call?
Service Gateway
141
143. Patterns are a good thing
Patterns can be difficult
Driven by example
Will make it easier
142
144. Fell free to download the PoEAA Workbench
http://w2ks.dei.isep.ipp.pt/psousa/GetFile.aspx
?file=PoEAAWorkbench.zip
Slides available thru SlideShare
http://www.slideshare.net/pagsousa
143
148. Fowler, Martin. Patterns of Enterprise Application Architecture. Adisson-Wesley.
Erich Gamma, Richard Helm, Ralph Johnson, John Vissides. Design patterns : elements of
reusable object-oriented software. Adisson-Wesley.
Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal. Pattern-
oriented Software Architecture: System of Patterns.
Buschmann, F.; Henney, K. And Schmidt, D. (2007) Pattern-Oriented Software Architecture: A
Pattern Language for Distributed Computing, Volume 4. Willey.
Deepak Alur, John Crupi and Dan Malks. Core J2EE Patterns: Best Practices and Design
Strategies. Prentice Hall / Sun Microsystems Press.
http://java.sun.com/blueprints/corej2eepatterns/index.html
Enterprise Solution Patterns Using Microsoft .NET. Microsoft Press.
http://msdn.microsoft.com/architecture/patterns/default.aspx?pull=/library/en-
us/dnpatterns/html/Esp.asp
Designing Data Tier Components and Passing Data Through Tiers. Microsoft Patterns &
Practices. http://msdn.microsoft.com/library/?url=/library/en-
us/dnbda/html/BOAGag.asp?frame=true
147
149. GoF Design patterns (em C#)
http://www.dofactory.com/Patterns/Patterns.aspx
GoF & POSA Design patterns (em Java)
http://www.vico.org/pages/PatronsDisseny.html
Patterns of Enterprise Application architecture
http://martinfowler.com/eaaCatalog/
Core J2EE Patterns
http://www.corej2eepatterns.com
Enterprise Solution Patterns Using Microsoft .NET.
http://msdn.microsoft.com/architecture/patterns/default.aspx?pull=/library/en-
us/dnpatterns/html/Esp.asp
Patterns of Enterprise Application Integration
http://www.enterpriseintegrationpatterns.com/
Enterprise Java Patterns @ The Server Side
http://www.theserverside.com/patterns/index.tss
Microsoft Data Patterns
http://msdn.microsoft.com/architecture/patterns/default.aspx?pull=/library/en-
us/dnpatterns/html/Dp.asp