SlideShare uma empresa Scribd logo
1 de 88
Lecture 04
Base Patterns
Agenda
 Base Patterns
– Gateway, Mapper, Layerd Supertype, Separated
Interface, Registry, Value Object, Plugin, Service
Stub, Record Set
 From Problem to Patterns
– Using design patterns
Reading
 Fowler 18
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
– All objects in the drawing layer must have an origin (x
and y) and implement Drawable
public abstract class Shape implements Drawable
{
protected int x,y;
}
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
Data Source Layer
Domain Layer
JDBC
Code
Interface
RowCallBackHandler
processRow(ResultSet rs)
Concreate class
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)
 Placing the Separated
Interfaced in a
third package
 When to use it
– When you need to break a dependency between two
parts of a system
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
 When to Use It
– As a last resort
public class Registry
{
private static Registry soleInstance = new Registry();
public static Registry getInstance()
{
return soleInstance;
}
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)
caller a plugin factory a plugin configuration
getPlugin
lookupPluginByType
new
a plugin
 A caller obtains a Plugin implementation of a
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
 reader.properties define the name of the actual
implementation class
ReaderClient ReaderFactory reader.properties
getFeedReader
props.getProperty("reader")
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=ReaderStub
reader.properties
Record Set (508)
An in-memory representation of tabular data
 Allows you to access database data from other
objects
– Scroll through a list of data
Record Set (508)
 How it Works
– Record set are usually provide by database classes
(JDBC or ADO.NET)
– Look exactly like the results of a database query
– Provides abstraction from the database code
 When to Use It
– When you need a common way to manipulate data
from a relational database
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
Using Design Patterns
Using Design Patterns
 Normally we don’t start with patterns
– We start with problems to solve
– From Problem to Pattern
 Must have clear objectives for the design
– The patterns will come as they are needed
 Establish Design Principles
– This applies to your application
 Remember the separation of concern
From Problem to Pattern
 How do I reuse common functionality of my
objects?
–Layered Supertype
 How do I access an external service without
becoming too dependant on it?
–Gateway
 How do I avoid creating unwanted
dependencies?
–Separated Interface
From Problem to Pattern
 How do I test my client code using a service that
I don’t have access to?
–Service Stub
 How do I link to my implementation class using
configuration
–Plugin
 How can I keep common object available within
the application
–Registry
Refactoring
 Design, redesign, refactor
– Make the design as complete as possible
– But be prepared to change design as you code
– Unit tests become very important
 Code Smell
– Think of your code as a baby:
“If it smells, change it!”
Refactoring
 Refactoring is the process of improving design in
little steps at a time
– Minimizes risks – calculated
– Changes are controlled
– Code can improve
– Less likely to smell
The Danger
 Code Dept
“I’ll fix it later”
The four most dangerous and expensive words in
programming
MailService
Mail Service
 We are building an web application
– One important service is sending messages in email
– We need to access the e-mail service
Mail Service
 We decide to use JavaMail API
– Problem is that this API is pretty low-level and
complicated
– Lots of “noise” – not good to have the domain
developers worry about that
What Design Pattern can we use here?
Mail Service Gateway
 We build a simple gateway to handle mail
– Domain developers don’t worry about the service
– We can easily change to a different mail API
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
MailSender (1/2)
 Class that sends the mail
– Method send that takes care of sending the mail
public class MailSender
{
public void send(String from, String to,
String subject, String body)
{
String smtpServer = "mail.ru.is";
try
{
MailSender (2/2)
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setText(body);
msg.setSentDate(new Date());
Transport.send(msg);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
MailSender
 Name the problem with his class
public class MailSender {
public void send(String from, String to, String subject, String body) {
String smtpServer = "mail.ru.is";
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setText(body);
msg.setSentDate(new Date());
Transport.send(msg);
} catch (Exception ex) { ex.printStackTrace(); }
}
}
MailSender
 Problem
– Many parameters instead of an object
– Mail server is hard-coded
– Exception handling is bad
public void send(String from, String to,
String subject, String body)
{
String smtpServer = ”smtp.ru.is";
try
{ ... }
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
MailService
 Interface for the domain developers
– Program-to-interfaces Principle
– So let MailSender implement this interface
public interface MailService
{
public void send(String from, String to,
String subject, String body);
}
public class MailSender implements MailService
{
public void send(String from, String to,
String subject, String body)
{ ...
Testing
 Testing MailService and MainSender is easy
public class TestMail
{
public static void main(String[] args)
{
MailService mail = new MailSender();
mail.send("andri@ru.is", // from
"andri@ru.is", // to
"Hallo", // subject
"So does this stuff work"); // body
}
}
Testing
TestMail: sending mail.
Done.
NOTE: mail.ru.is is not good for testing!
Testing
 What is the problem with clients like this?
public class TestMail
{
public static void main(String[] args)
{
MailService mail = new MailSender();
mail.send("andri@ru.is", // from
"andri@ru.is", // to
"Hallo", // subject
"So does this stuff work"); // body
}
}
Improvements
 Problem
– MailSender implementation class is exposed to the
domain layer
 Solution
– Use the Plugin Pattern
– Create a factory that will read a configuration file
and load the mail implementation class
– Client will use the MailService interface
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: one plugin for test, another for production
Factory with a Plugin
 Create a MailFactory class
– Loads mail.properties file
– Creates the class specified in the properties file and
returns interface MailService
– Clients use MailService and are not exposed to
particular implementation
– It’s easy to change the properties file
Improvements
 Problem
– Can we make the loading of properties and class more
generic?
– Other factories might need this functionality also
 Solution:
– Create a Layered Supertype
– MailFactory extends Factory
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)
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
Plugin Pattern
Factory
 Has two methods
– loadProperties
– loadClass
 Exception handling
– Create a new exception class that we will use
– FactoyException
– Log the error
FactoryException
 Extends Exception
– Checked exception
– Callers must catch this exception or explicitly throw it
public class FactoryException extends Exception
{
public FactoryException(String message)
{
super(message);
}
public FactoryException(String message, Throwable cause)
{
super(message, cause);
}
}
Factory
public class Factory {
Logger logger = Logger.getLogger(LogInfo.LOG_NAME);
protected Properties loadProperties(String filename)
throws FactoryException {
Properties props = new Properties();
try
{
props.load(new FileInputStream(new File(filename)));
}
catch (FileNotFoundException fnfex)
{
String msg = "Factoy: File '" + filename + "' not found.";
logger.severe(msg);
throw new FactoryException(msg, fnfex);
}
...
return props;
}
Testing Fails
 Exception is thrown and message is logged
2.9.2007 16:49:34 is.ru.honn.rubook.factory.Factory loadClass
SEVERE: Factoy: Class 'is.ru.honn.rubook.mail.MailServiceStubx' not found.
Testing Fails
 Problem
– MailService implementation classes have to
handle FactoryException or pass it on
– Do we want clients to worry about some factory?
 Solution
– One solution is to catch FactoryException and
throw unchecked MailService exception
MailFactory
public class MailFactory extends Factory
{
public MailService getMailService()
{
MailService service;
try
{
service = (MailService)loadClass(
loadProperties("mail.properties").
getProperty("mail.service.class"));
}
catch(FactoryException fex)
{
throw new MailServiceException ("Unable to send e-mail", fex);
}
return service;
}
}
MailServiceException
 Extends RuntimeException
– Unchecked exception
– Callers decide if they want to catch it
public class MailServiceException extends RuntimeException
{
public MailServiceException(String message)
{
super(message);
}
public MailServiceException(String message, Throwable cause)
{
super(message, cause);
}
}
Testing
 Using the MailFactory class
– We can catch the MailServiceException or ignore it
– Notice we have not only abstracted the Mail API but
also the exception handling
public class TestMail
{
public static void main(String[] args)
{
MailFactory mf = new MailFactory();
MailService mail = mf.getMailService();
mail.send("andri@ru.is", "andri@ru.is", "Hello", "Hello");
}
}
Improvements
 Problem
– Exception handling in our original MailSender is bad
 Solution
– Use the MailServiceException
public void send(MailMessage message)
{
try { ... }
catch (Exception ex)
{
String msg = "Sending mail failed: " + ex.getMessage();
logger.severe(msg);
throw new MailServiceException(msg, ex);
}
SEVERE: Sending mail failed: Unknown SMTP host: mail.ru.is
Improvements
 Problem
– What if we don’t have access to the SMTP server
at this time?
 Solution
– Use a Service Stub
– Create the class MailServiceStub that will simply log out
the mail sent
– Could also write in file
Service Stub (504)
Removes dependence upon problematic
services during testing
 Enterprise systems often need to access
external system
– Can be out of developers control
MailServiceStub
public class MailServiceStub implements MailService
{
Logger logger = Logger.getLogger(LogInfo.LOG_NAME);
public void send(String from, String to,
String subject, String body)
{
logger.info("Sending mail from '" + from + "' to '" + to +
"' Subject: '" + subject);
}
}
2.9.2007 16:36:08 is.ru.honn.rubook.mail.MailServiceStub send
INFO: Sending mail from 'andri@ru.is' to 'andri@ru.is' Subject: 'Hello
mail.service.class=is.ru.honn.rubook.mail.MailServiceStub
mail.properties
Improvements
 Problem
– What if we need to add new parameter?
 Solution
– Use an object to group parameters
– Easy to change without changing the interface
public interface MailService {
public void send(String from, String to,
String subject, String body);
}
public interface MailService
{
public void send(MailMessage message);
}
MailMessage
 Typical Data Transfer Object
public class MailMessage {
private String from;
private String to;
private String subject;
private String body;
public MailMessage(String from, String to,
String subject, String body)
{
this.from = from;
this.to = to;
this.subject = subject;
this.body = body;
}
public String getFrom() { return from; }
public void setFrom(String from) { this.from = from; }
...
Improvements
 Problem
– The mail server in MailSender is still hardcoded
 Solution
– Place in the configuration file
– Let the factory inject the name into the
Mail Service
public interface MailService
{
public void setMailServer(String mailServer);
public void send(MailMessage message);
}
Injecting the Mail Server Name
New MailFactoy
 getMailService injects the name into the service
public class MailFactory extends Factory
{
public MailService getMailService()
{
...
loadProperties("mail.properties");
service = (MailService)loadClass(getProperties().
getProperty("mail.service.class"));
service.setMailServer(getProperties().
getProperty("mail.server")); // injection
return service;
}
}
mail.service.class=is.ru.honn.rubook.mail.MailSender
mail.server=mail.ru.is
Improvements
 Problem
– loadProperties loads the file each time used
 Solution
– Load once then use
public class Factory
{
private Properties properties = new Properties();
protected Properties loadProperties(String filename) throws FactoryException
{ ...
return properties;
}
public Properties getProperties()
{
return properties;
} ...
Improvements
 Problem
– All mail server implementations must store server name
and set function
– Common functionality in multiple classes
 Solution
– Create a Layered Supertype
– Take care of the common functionality
– Make the send method abstract
AbstractMailService
 Implements MailService
– Provides handling of the mail server property
public abstract class AbstractMailService implements MailService
{
protected String mailServer;
// this is used by the factory to inject
public void setMailServer(String mailServer)
{
this.mailServer = mailServer;
}
public String getMailServer()
{
return mailServer;
}
}
MailSender
 Extends AbstractMailService
– Does not have to implement the MailServer interface
– Can use the getMailServer method
public class MailSender extends AbstractMailService
{
public void send(MailMessage message)
{
try
{
Properties props = System.getProperties();
props.put("mail.smtp.host", getMailServer());
...
Summary
 Base Patterns
• Gateway, Mapper, Layerd Supertype, Separated Interface, Registry,
Value Object, Plugin, Service Stub, Record Set
 We start with problems to solve
– Then we find the patterns to use
– Must have clear objectives for the design
 Beware of code smell
 Refactoring is the process of improving design in
little steps at a time
 Example case study
– Mail service with a configurable factory

Mais conteúdo relacionado

Mais procurados

ApacheCon North America 2018: Creating Spark Data Sources
ApacheCon North America 2018: Creating Spark Data SourcesApacheCon North America 2018: Creating Spark Data Sources
ApacheCon North America 2018: Creating Spark Data SourcesJayesh Thakrar
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its ModuleMuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its ModuleJitendra Bafna
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...jaxLondonConference
 
The Adventure: BlackRay as a Storage Engine
The Adventure: BlackRay as a Storage EngineThe Adventure: BlackRay as a Storage Engine
The Adventure: BlackRay as a Storage Enginefschupp
 
Dao pattern
Dao patternDao pattern
Dao patternciriako
 
Easy Dataweave transformations - Ashutosh
Easy Dataweave transformations - AshutoshEasy Dataweave transformations - Ashutosh
Easy Dataweave transformations - AshutoshStrawhatLuffy11
 
Presentazione jrc 24 ottobre
Presentazione jrc 24 ottobrePresentazione jrc 24 ottobre
Presentazione jrc 24 ottobresmespire
 
SQLPASS AD501-M XQuery MRys
SQLPASS AD501-M XQuery MRysSQLPASS AD501-M XQuery MRys
SQLPASS AD501-M XQuery MRysMichael Rys
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Igor Anishchenko
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginnersRahul Jain
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersllangit
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldevllangit
 
SQL and NoSQL in SQL Server
SQL and NoSQL in SQL ServerSQL and NoSQL in SQL Server
SQL and NoSQL in SQL ServerMichael Rys
 

Mais procurados (20)

Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
ApacheCon North America 2018: Creating Spark Data Sources
ApacheCon North America 2018: Creating Spark Data SourcesApacheCon North America 2018: Creating Spark Data Sources
ApacheCon North America 2018: Creating Spark Data Sources
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its ModuleMuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
 
Day4
Day4Day4
Day4
 
The Adventure: BlackRay as a Storage Engine
The Adventure: BlackRay as a Storage EngineThe Adventure: BlackRay as a Storage Engine
The Adventure: BlackRay as a Storage Engine
 
Dao pattern
Dao patternDao pattern
Dao pattern
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Easy Dataweave transformations - Ashutosh
Easy Dataweave transformations - AshutoshEasy Dataweave transformations - Ashutosh
Easy Dataweave transformations - Ashutosh
 
Presentazione jrc 24 ottobre
Presentazione jrc 24 ottobrePresentazione jrc 24 ottobre
Presentazione jrc 24 ottobre
 
Data access
Data accessData access
Data access
 
SQLPASS AD501-M XQuery MRys
SQLPASS AD501-M XQuery MRysSQLPASS AD501-M XQuery MRys
SQLPASS AD501-M XQuery MRys
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldev
 
SQL and NoSQL in SQL Server
SQL and NoSQL in SQL ServerSQL and NoSQL in SQL Server
SQL and NoSQL in SQL Server
 

Destaque (15)

L06 process design
L06 process designL06 process design
L06 process design
 
New Technology 2015 L02 A Journey Exploring Technology
New Technology 2015 L02 A Journey Exploring TechnologyNew Technology 2015 L02 A Journey Exploring Technology
New Technology 2015 L02 A Journey Exploring Technology
 
L05 Innovation
L05 InnovationL05 Innovation
L05 Innovation
 
L07 Becoming Invisible
L07 Becoming InvisibleL07 Becoming Invisible
L07 Becoming Invisible
 
L05 Frameworks
L05 FrameworksL05 Frameworks
L05 Frameworks
 
New Technology 2015 L03 Exponential World
New Technology 2015 L03 Exponential WorldNew Technology 2015 L03 Exponential World
New Technology 2015 L03 Exponential World
 
Responsible gaming in the Online Internet World
Responsible gaming in the Online Internet WorldResponsible gaming in the Online Internet World
Responsible gaming in the Online Internet World
 
New gambling options with digital gaming platforms
New gambling options with digital gaming platforms New gambling options with digital gaming platforms
New gambling options with digital gaming platforms
 
L04 Adjacent Possible
L04 Adjacent PossibleL04 Adjacent Possible
L04 Adjacent Possible
 
L03 Design Patterns
L03 Design PatternsL03 Design Patterns
L03 Design Patterns
 
L02 Software Design
L02 Software DesignL02 Software Design
L02 Software Design
 
New Technology Lecture L16 A Worldwide Network
New Technology Lecture L16 A Worldwide NetworkNew Technology Lecture L16 A Worldwide Network
New Technology Lecture L16 A Worldwide Network
 
L06 Diffusion of Innovation
L06 Diffusion of InnovationL06 Diffusion of Innovation
L06 Diffusion of Innovation
 
New Technology 2016 L01 Introduction
New Technology 2016 L01 IntroductionNew Technology 2016 L01 Introduction
New Technology 2016 L01 Introduction
 
L01 Enterprise Application Architecture
L01 Enterprise Application ArchitectureL01 Enterprise Application Architecture
L01 Enterprise Application Architecture
 

Semelhante a L04 base patterns

Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016Sumo Logic
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Brian S. Paskin
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHPPaul Jones
 
Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with springSreenivas Kappala
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingAllan Mangune
 
Apache Eagle in Action
Apache Eagle in ActionApache Eagle in Action
Apache Eagle in ActionHao Chen
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphonyBrahampal Singh
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenchesIsmail Mayat
 
Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Tjarda Peelen
 
Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎
Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎
Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎Qingwen zhao
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS BackendLaurent Cerveau
 
Sumo Logic Quickstart Training 10/14/2015
Sumo Logic Quickstart Training 10/14/2015Sumo Logic Quickstart Training 10/14/2015
Sumo Logic Quickstart Training 10/14/2015Sumo Logic
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdfssuser0562f1
 

Semelhante a L04 base patterns (20)

L06 Using Design Patterns
L06 Using Design PatternsL06 Using Design Patterns
L06 Using Design Patterns
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHP
 
.Net template solution architecture
.Net template solution architecture.Net template solution architecture
.Net template solution architecture
 
Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with spring
 
Vip2p
Vip2pVip2p
Vip2p
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & Programming
 
Apache Eagle in Action
Apache Eagle in ActionApache Eagle in Action
Apache Eagle in Action
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphony
 
Puppet: From 0 to 100 in 30 minutes
Puppet: From 0 to 100 in 30 minutesPuppet: From 0 to 100 in 30 minutes
Puppet: From 0 to 100 in 30 minutes
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501
 
Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎
Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎
Apache Eagle: 来自eBay的分布式实时Hadoop数据安全引擎
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
Sumo Logic Quickstart Training 10/14/2015
Sumo Logic Quickstart Training 10/14/2015Sumo Logic Quickstart Training 10/14/2015
Sumo Logic Quickstart Training 10/14/2015
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
Apache Eagle: Secure Hadoop in Real Time
Apache Eagle: Secure Hadoop in Real TimeApache Eagle: Secure Hadoop in Real Time
Apache Eagle: Secure Hadoop in Real Time
 

Mais de Ó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
 

Mais de Ó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
 

Último

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

L04 base patterns

  • 2. Agenda  Base Patterns – Gateway, Mapper, Layerd Supertype, Separated Interface, Registry, Value Object, Plugin, Service Stub, Record Set  From Problem to Patterns – Using design patterns
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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; }
  • 11. Example: Drawing system  Shape class revisited – All objects in the drawing layer must have an origin (x and y) and implement Drawable public abstract class Shape implements Drawable { protected int x,y; }
  • 12. 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
  • 13. Separated Interface  Layered System – Domain layer depends on Data Source layer – Data Source layer cannot access Domain layer Data Source Layer Domain Layer JDBC Code Interface RowCallBackHandler processRow(ResultSet rs) Concreate class RowCallBackHandler processRow(ResultSet rs) implements Code reading SQL Execution calls Separated interface
  • 14. Separated Interface (476)  Implementation is placed in a separate package Developers of the client package are responsible for the interface
  • 15. Separated Interface (476)  Placing the Separated Interfaced in a third package  When to use it – When you need to break a dependency between two parts of a system
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. Singleton Registry (480)  Only one instance running  When to Use It – As a last resort public class Registry { private static Registry soleInstance = new Registry(); public static Registry getInstance() { return soleInstance; } private Registry() { } ... } Registry registry = Registry.getInstance(); //registry = new Registry (); Does not work
  • 21. 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
  • 22. 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()); } ...
  • 23. 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
  • 24. 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
  • 25. Plugin (499) caller a plugin factory a plugin configuration getPlugin lookupPluginByType new a plugin  A caller obtains a Plugin implementation of a separated interface  When to Use It – Use plugin when you have behavior that requires different implementations based on runtime environment
  • 26. Plugin (499)  ReaderClient uses ReaderFactory to get an interface to FeedReader  reader.properties define the name of the actual implementation class ReaderClient ReaderFactory reader.properties getFeedReader props.getProperty("reader") new FeedReader
  • 27. 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
  • 28. Service Stub (504) Removes dependence upon problematic services during testing  Enterprise systems often need to access external system – Can be out of developers control
  • 29. 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
  • 30. 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=ReaderStub reader.properties
  • 31. Record Set (508) An in-memory representation of tabular data  Allows you to access database data from other objects – Scroll through a list of data
  • 32. Record Set (508)  How it Works – Record set are usually provide by database classes (JDBC or ADO.NET) – Look exactly like the results of a database query – Provides abstraction from the database code  When to Use It – When you need a common way to manipulate data from a relational database
  • 33.
  • 34. 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
  • 35. QUIZ
  • 36. 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
  • 37. 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
  • 38. Question #3  Sketch of a pattern is his A) Plugin B) Mapper C) Registry D) Service Stub
  • 39. 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
  • 41. Using Design Patterns  Normally we don’t start with patterns – We start with problems to solve – From Problem to Pattern  Must have clear objectives for the design – The patterns will come as they are needed  Establish Design Principles – This applies to your application  Remember the separation of concern
  • 42. From Problem to Pattern  How do I reuse common functionality of my objects? –Layered Supertype  How do I access an external service without becoming too dependant on it? –Gateway  How do I avoid creating unwanted dependencies? –Separated Interface
  • 43. From Problem to Pattern  How do I test my client code using a service that I don’t have access to? –Service Stub  How do I link to my implementation class using configuration –Plugin  How can I keep common object available within the application –Registry
  • 44. Refactoring  Design, redesign, refactor – Make the design as complete as possible – But be prepared to change design as you code – Unit tests become very important  Code Smell – Think of your code as a baby: “If it smells, change it!”
  • 45. Refactoring  Refactoring is the process of improving design in little steps at a time – Minimizes risks – calculated – Changes are controlled – Code can improve – Less likely to smell
  • 46. The Danger  Code Dept “I’ll fix it later” The four most dangerous and expensive words in programming
  • 48. Mail Service  We are building an web application – One important service is sending messages in email – We need to access the e-mail service
  • 49. Mail Service  We decide to use JavaMail API – Problem is that this API is pretty low-level and complicated – Lots of “noise” – not good to have the domain developers worry about that What Design Pattern can we use here?
  • 50. Mail Service Gateway  We build a simple gateway to handle mail – Domain developers don’t worry about the service – We can easily change to a different mail API
  • 51. 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
  • 52. MailSender (1/2)  Class that sends the mail – Method send that takes care of sending the mail public class MailSender { public void send(String from, String to, String subject, String body) { String smtpServer = "mail.ru.is"; try {
  • 53. MailSender (2/2) Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject); msg.setText(body); msg.setSentDate(new Date()); Transport.send(msg); } catch (Exception ex) { ex.printStackTrace(); } } }
  • 54. MailSender  Name the problem with his class public class MailSender { public void send(String from, String to, String subject, String body) { String smtpServer = "mail.ru.is"; try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false)); msg.setSubject(subject); msg.setText(body); msg.setSentDate(new Date()); Transport.send(msg); } catch (Exception ex) { ex.printStackTrace(); } } }
  • 55. MailSender  Problem – Many parameters instead of an object – Mail server is hard-coded – Exception handling is bad public void send(String from, String to, String subject, String body) { String smtpServer = ”smtp.ru.is"; try { ... } catch (Exception ex) { ex.printStackTrace(); } } }
  • 56. MailService  Interface for the domain developers – Program-to-interfaces Principle – So let MailSender implement this interface public interface MailService { public void send(String from, String to, String subject, String body); } public class MailSender implements MailService { public void send(String from, String to, String subject, String body) { ...
  • 57. Testing  Testing MailService and MainSender is easy public class TestMail { public static void main(String[] args) { MailService mail = new MailSender(); mail.send("andri@ru.is", // from "andri@ru.is", // to "Hallo", // subject "So does this stuff work"); // body } }
  • 58. Testing TestMail: sending mail. Done. NOTE: mail.ru.is is not good for testing!
  • 59. Testing  What is the problem with clients like this? public class TestMail { public static void main(String[] args) { MailService mail = new MailSender(); mail.send("andri@ru.is", // from "andri@ru.is", // to "Hallo", // subject "So does this stuff work"); // body } }
  • 60. Improvements  Problem – MailSender implementation class is exposed to the domain layer  Solution – Use the Plugin Pattern – Create a factory that will read a configuration file and load the mail implementation class – Client will use the MailService interface
  • 61. 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: one plugin for test, another for production
  • 62. Factory with a Plugin  Create a MailFactory class – Loads mail.properties file – Creates the class specified in the properties file and returns interface MailService – Clients use MailService and are not exposed to particular implementation – It’s easy to change the properties file
  • 63. Improvements  Problem – Can we make the loading of properties and class more generic? – Other factories might need this functionality also  Solution: – Create a Layered Supertype – MailFactory extends Factory
  • 64. 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
  • 65. 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
  • 67. Factory  Has two methods – loadProperties – loadClass  Exception handling – Create a new exception class that we will use – FactoyException – Log the error
  • 68. FactoryException  Extends Exception – Checked exception – Callers must catch this exception or explicitly throw it public class FactoryException extends Exception { public FactoryException(String message) { super(message); } public FactoryException(String message, Throwable cause) { super(message, cause); } }
  • 69. Factory public class Factory { Logger logger = Logger.getLogger(LogInfo.LOG_NAME); protected Properties loadProperties(String filename) throws FactoryException { Properties props = new Properties(); try { props.load(new FileInputStream(new File(filename))); } catch (FileNotFoundException fnfex) { String msg = "Factoy: File '" + filename + "' not found."; logger.severe(msg); throw new FactoryException(msg, fnfex); } ... return props; }
  • 70. Testing Fails  Exception is thrown and message is logged 2.9.2007 16:49:34 is.ru.honn.rubook.factory.Factory loadClass SEVERE: Factoy: Class 'is.ru.honn.rubook.mail.MailServiceStubx' not found.
  • 71. Testing Fails  Problem – MailService implementation classes have to handle FactoryException or pass it on – Do we want clients to worry about some factory?  Solution – One solution is to catch FactoryException and throw unchecked MailService exception
  • 72. MailFactory public class MailFactory extends Factory { public MailService getMailService() { MailService service; try { service = (MailService)loadClass( loadProperties("mail.properties"). getProperty("mail.service.class")); } catch(FactoryException fex) { throw new MailServiceException ("Unable to send e-mail", fex); } return service; } }
  • 73. MailServiceException  Extends RuntimeException – Unchecked exception – Callers decide if they want to catch it public class MailServiceException extends RuntimeException { public MailServiceException(String message) { super(message); } public MailServiceException(String message, Throwable cause) { super(message, cause); } }
  • 74. Testing  Using the MailFactory class – We can catch the MailServiceException or ignore it – Notice we have not only abstracted the Mail API but also the exception handling public class TestMail { public static void main(String[] args) { MailFactory mf = new MailFactory(); MailService mail = mf.getMailService(); mail.send("andri@ru.is", "andri@ru.is", "Hello", "Hello"); } }
  • 75. Improvements  Problem – Exception handling in our original MailSender is bad  Solution – Use the MailServiceException public void send(MailMessage message) { try { ... } catch (Exception ex) { String msg = "Sending mail failed: " + ex.getMessage(); logger.severe(msg); throw new MailServiceException(msg, ex); } SEVERE: Sending mail failed: Unknown SMTP host: mail.ru.is
  • 76. Improvements  Problem – What if we don’t have access to the SMTP server at this time?  Solution – Use a Service Stub – Create the class MailServiceStub that will simply log out the mail sent – Could also write in file
  • 77. Service Stub (504) Removes dependence upon problematic services during testing  Enterprise systems often need to access external system – Can be out of developers control
  • 78. MailServiceStub public class MailServiceStub implements MailService { Logger logger = Logger.getLogger(LogInfo.LOG_NAME); public void send(String from, String to, String subject, String body) { logger.info("Sending mail from '" + from + "' to '" + to + "' Subject: '" + subject); } } 2.9.2007 16:36:08 is.ru.honn.rubook.mail.MailServiceStub send INFO: Sending mail from 'andri@ru.is' to 'andri@ru.is' Subject: 'Hello mail.service.class=is.ru.honn.rubook.mail.MailServiceStub mail.properties
  • 79. Improvements  Problem – What if we need to add new parameter?  Solution – Use an object to group parameters – Easy to change without changing the interface public interface MailService { public void send(String from, String to, String subject, String body); } public interface MailService { public void send(MailMessage message); }
  • 80. MailMessage  Typical Data Transfer Object public class MailMessage { private String from; private String to; private String subject; private String body; public MailMessage(String from, String to, String subject, String body) { this.from = from; this.to = to; this.subject = subject; this.body = body; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } ...
  • 81. Improvements  Problem – The mail server in MailSender is still hardcoded  Solution – Place in the configuration file – Let the factory inject the name into the Mail Service public interface MailService { public void setMailServer(String mailServer); public void send(MailMessage message); }
  • 82. Injecting the Mail Server Name
  • 83. New MailFactoy  getMailService injects the name into the service public class MailFactory extends Factory { public MailService getMailService() { ... loadProperties("mail.properties"); service = (MailService)loadClass(getProperties(). getProperty("mail.service.class")); service.setMailServer(getProperties(). getProperty("mail.server")); // injection return service; } } mail.service.class=is.ru.honn.rubook.mail.MailSender mail.server=mail.ru.is
  • 84. Improvements  Problem – loadProperties loads the file each time used  Solution – Load once then use public class Factory { private Properties properties = new Properties(); protected Properties loadProperties(String filename) throws FactoryException { ... return properties; } public Properties getProperties() { return properties; } ...
  • 85. Improvements  Problem – All mail server implementations must store server name and set function – Common functionality in multiple classes  Solution – Create a Layered Supertype – Take care of the common functionality – Make the send method abstract
  • 86. AbstractMailService  Implements MailService – Provides handling of the mail server property public abstract class AbstractMailService implements MailService { protected String mailServer; // this is used by the factory to inject public void setMailServer(String mailServer) { this.mailServer = mailServer; } public String getMailServer() { return mailServer; } }
  • 87. MailSender  Extends AbstractMailService – Does not have to implement the MailServer interface – Can use the getMailServer method public class MailSender extends AbstractMailService { public void send(MailMessage message) { try { Properties props = System.getProperties(); props.put("mail.smtp.host", getMailServer()); ...
  • 88. Summary  Base Patterns • Gateway, Mapper, Layerd Supertype, Separated Interface, Registry, Value Object, Plugin, Service Stub, Record Set  We start with problems to solve – Then we find the patterns to use – Must have clear objectives for the design  Beware of code smell  Refactoring is the process of improving design in little steps at a time  Example case study – Mail service with a configurable factory