SlideShare a Scribd company logo
1 of 72
Lecture 05
Frameworks
Agenda
 Why frameworks?
 Framework patterns
– Inversion of Control and Dependency Injection
– Template Method
– Strategy
 From problems to patterns
– Game Framework
 Spring framework
– Bean containers
– BeanFactory and ApplicationContext
Reading
 Dependency Injection
 Template Method Pattern
 Strategy Pattern
 Spring Framework (video)
 Article by Fowler
– Inversion of Control Containers and the Dependency
Injection pattern
Resources
 Spring Framework homepage
– http://www.springframework.org
 Reference Documentation
– http://www.springframework.org/docs/reference/index.
html
– Also in PDF format
Why Frameworks?
Why use Frameworks?
 Frameworks can increase productivity
– We can create our own framework
– We can use some third party framework
 Frameworks implement general functionality
– We use the framework to implement our business
logic
Framework design
 Inheritance of framework classes
 Composition of framework classes
 Implementation of framework interfaces
 Dependency Injection
Framework
Your Code
Domain ?
Using Frameworks
 Frameworks are concrete, not abstract
– Design patterns are conceptual, frameworks provide
building blocks
 Frameworks are higher-level
– Built on design patterns
 Frameworks are usually general or technology-
specific
 Good frameworks are simple to use, yet
powerful
Abstractions
 From API to Frameworks
API Definition JEE/.NET API
API Patterns JEE/.NET
Patterns
Framework Spring
Open Source Frameworks
 Web Frameworks
– Jakarta Struts, WebWork, Maverick, Play!
 Database Frameworks
– Hibernate, JDO, TopLink
 General Framework
– Spring, Expresso, PicoContainer, Avalon
 Platform Frameworks
– JEE
Where do Frameworks Come
From?
 Who spends their time writing frameworks?
 If they give them away, how can anyone make
money?
 Companies that use frameworks, have their
developers work on them
 Give the code, sell the training and consulting
Write down the pros and cons (benefits and drawbacks) for frameworks.
Use two columns, benefits on the left, drawbacks right
EXERCISE
Pros and Cons
 Pros
– Productivity
– Well know application
models and patterns
– Tested functionality
– Connection of different
components
– Use of open standards
 Cons
– Can be complicated,
learning curve
– Dependant on frameworks,
difficult to change
– Difficult to debug and find
bugs
– Performance problems can
be difficult
– Can be bought by an evil
company
Framework Patterns
Separation of Concerns
 One of the main challenge of frameworks is to
provide separation of concerns
– Frameworks deal with generic functionality
– Layers of code
 Frameworks need patterns to combine generic and
domain specific functionality
Framework Patterns
 Useful patterns when building a framework:
– Dependency Injection: remove dependencies by
injecting them (sometimes called Inversion of Control)
– Template Method: extend a generic class and provide
specific functionality
– Strategy: Implement an interface to provide specific
functionality
Dependency Injection
Removes explicit dependence on specific
application code by injecting depending classes
into the framework
 Objects and interfaces are injected into the
classes that to the work
 Two types of injection
– Setter injection: using set methods
– Constructor injection: using constructors
Dependency Injection
 Fowler’s Naive Example
– MovieLister uses a finder class
– How can we separate the finder functionality?
class MovieLister...
public Movie[] moviesDirectedBy(String arg) {
List allMovies = finder.findAll();
for (Iterator it = allMovies.iterator(); it.hasNext();) {
Movie movie = (Movie) it.next();
if (!movie.getDirector().equals(arg)) it.remove();
}
return (Movie[])allMovies.toArray(new Movie[allMovies.size()]);
}
Separate what varies
REMEMBER PROGRAM TO INTERFACES PRINSIPLE?
Dependency Injection
 Fowler’s Naive Example
– Let’s make an interface, MovieFinder
– MovieLister is still dependent on particular
MovieFinder implementation
public interface MovieFinder {
List findAll();
}
class MovieLister...
private MovieFinder finder;
public MovieLister() {
finder = new MovieFinderImpl("movies1.txt");
}
Argh!
Not cool.
Dependency Injection
 An assembler (or container) is used to create an
implementation
– Using constructor injection, the assember will create a
MovieLister and passing a MovieFinder interface in the
contructor
– Using setter injection, the assembler will create
MovieLister and then all the setFinder setter
method to provide the
MovieFinder interface
Dependency Injection
 Example setter injection
class MovieLister...
private MovieFinder finder;
public void setFinder(MovieFinder finder) {
this.finder = finder;
}
class MovieFinderImpl...
public void setFilename(String filename)
this.filename = filename;
}
Dependency Injection
SEPARATED INTERFACE
Example
 ContentLister
public class ContentLister
{
private ContentFinder contentFinder;
public void setContentFinder(ContentFinder contentFinder)
{
this.contentFinder = contentFinder;
}
public List<Content> find(String pattern)
{
return contentFinder.find(pattern);
}
}
Example
 ContentFinder interface
public interface ContentFinder
{
List<Content> find(String pattern);
}
Example
 SimpleContentFinder – implementation
public class SimpleContentFinder implements ContentFinder
{
...
public List<Content> find(String pattern)
{
List<Content> contents = contentService.getContents();
List<Content> newList = new ArrayList<Content>();
for(Content c : contents)
{
if (c.getTitle().toLowerCase().contains(pattern))
{
newList.add(c);
}
}
return newList;
}
}
Example
 TestContentLister - Testcase
public class TestContentLister extends TestCase {
public void testContentLister () {
ServiceFactoryserviceFactory = new ServiceFactory();
ContentServicecontentService = (ContentService)
serviceFactory.getService("contentService");
contentService.addContent(new Content(1, "The Simpsons Movie", "", "", new Date()
contentService.addContent(new Content(1, "The Bourne Ultimatum", "", "", new Date
contentService.addContent(new Content(1, "Rush Hour 3", "", "", new Date(), ""));
ContentFindercontentFinder = new
SimpleContentFinder(contentService);
ContentListercontentLister = new ContentLister();
contentLister.setContentFinder(contentFinder);
List<Content>searchResults = contentLister.find("simpsons");
for (Content c : searchResults) { System.out.println(c); }
}
}
Magic stuff
Example
Template Method Pattern
Create a template for steps of an algorithm and let
subclasses extend to provide specific
functionality
 We know the steps in an algorithm and the order
– We don’t know specific functionality
 How it works
– Create an abstract superclass that can be extended
for the specific functionality
– Superclass will call the abstract methods when
needed
Template Method Pattern
Template Method Pattern
public class AbstractOrderEJB
{
public final Invoice placeOrder(int customerId,
InvoiceItem[] items)
throws NoSuchCustomerException, SpendingLimitViolation
{
int total = 0;
for (int i=0; i < items.length; i++)
{
total += getItemPrice(items[i]) * items[i].getQuantity();
}
if (total >getSpendingLimit(customerId))
{
...
}
else if (total > DISCOUNT_THRESHOLD) ...
int invoiceId = placeOrder(customerId, total, items);
...
}
}
Template Method Pattern
AbstractOrderEJB
placeOrder ()
abstract getItemPrice()
abstract getSpendingLimit()
abstract placeOrder()
MyOrderEJB
getItemPrice()
getSpendingLimit()
placeOrder()
extends
Domain
specific
functionality
Generic
functionality
Template Method Pattern
public class MyOrderEJB extends AbstractOrderEJB
{
...
int getItemPrice(int[] i)
{
...
}
int getSpendingLimit(int customerId)
{
...
}
int placeOrder(int customerId, int total, int items)
{
...
}
}
Template Method Pattern
 When to Use it
– For processes where steps are know but some steps
need to be changed
– Works if same team is doing the abstract and the
concrete class
 When Not to Use it
– The concrete class is forced to inherit, limits
possibilities
– Developer of the concrete class must understand the
abstract calls
– If another team is doing the concrete class as this
Strategy Pattern
Create a template for the steps of an algorithm
and inject the specific functionality
 Implement an interface to provide specific
functionality
– Algorithms can be selected on-the-fly at runtime
depending on conditions
– Similar as Template Method but uses interface
inheritance
Strategy Pattern
 How it works
– Create an interface to use in the generic algorithm
– Implementation of the interface provides the specific
functionality
– Framework class has reference to the interface an
– Setter method for the interface
Strategy Pattern
Strategy Pattern
 Interface for specific functionality
 Generic class uses the interface
– Set method to inject the interface
public interface DataHelper
{
int getItemPrice(InvoiceItem item);
int getSpendingLimit(CustomerId) throws NoSuchCustomerException;
int palceOrder(int customerId, int total, InvoiceItem[] items);
}
private DataHelper dataHelper;
public void setDataHelper(DataHelper newDataHelper)
{
this.dataHelper = newDataHelper;
}
DEPENDENCY INJECTION
Strategy Pattern
public class OrderEJB
{
public final Invoice placeOrder(int customerId, InvoiceItem[] items)
throws NoSuchCustomerException, SpendingLimitViolation
{
int total = 0;
for (int i=0; i < items.length; i++)
{
total += this.dataHelper.getItemPrice(items[i]) *
items[i].getQuantity();
}
if (total >this.dataHelper.getSpendingLimit(customerId))
{...
}
else if (total > DISCOUNT_THRESHOLD) ...
int invoiceId = this.dataHelper.placeOrder(customerId,
total, items);
...
}
}
We are building framework for games. It turns out that all the games
are similar so we create an abstract class for basic functionality that
does not change, and then extend that class for each game. What
pattern is this?
A) Layered Supertype
B) Template Method
C) Strategy
D) Dependency Injection
QUIZ
✔
From Problem to Patterns
Framework design
 Inheritance of framework classes
Template Method – class Inheritance
 Composition of framework classes
Strategy – interface Inheritance
Dependency Injection
Framework
Your Code
Domain ?
From Problem to Pattern
We need to design game software
Common turn-based board games like monopoly,
chess, backgammon, yatzy etc.
You must propose a design
From Problem to Pattern
Let’s make a Game Framework
What patterns can we use?
Patterns
 Template Method
– Template of an algorithm
– Based on class inheritance
 Strategy
– Composition of an strategy
– Based on interface inheritance
Template Method Pattern
Create a template for steps of an algorithm and let
subclasses extend to provide specific
functionality
 We know the steps in an algorithm and the order
– We don’t know specific functionality
 How it works
– Create an abstract superclass that can be extended
for the specific functionality
– Superclass will call the abstract methods when
needed
What is the game algorithm?
initialize
while more plays
make one turn
print winnner
void initializeGame();
boolean endOfGame();
void makePlay(int player);
void printWinner();
Game Template
Specific Game
extends
This is the generic
template of the game
play
This is the specific details
for this specific game
Design
interface
Game
void initializeGame
void makePlay (int player)
boolean endOfGame
void printWinner
AbstractGame
playOneGame
(int playerCount)
implements
Chess
void initializeGame
void makePlay(int player)
boolean endOfGame
void printWinner
implements
Interface for game algorithm
package is.ru.honn.game.framework;
public interface Game
{
public void initializeGame();
public void makePlay(int player);
public boolean endOfGame();
public void printWinner();
}
The Template
package is.ru.honn.game.framework;
public abstract class AbstractGame implements Game
{
protected int playersCount;
public final void playOneGame(int playersCount)
{
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
The Specific Game
class Chess extends AbstractGame
{
public void initializeGame()
{
// Initialize players, put the pieces on the board
}
public void makePlay(int player)
{
// Process a turn for the player
}
public boolean endOfGame()
{
// Return true if in Checkmate or stalemate
return true;
}
public void printWinner()
{
// Display the winning player
}
}
Design
interface
Game
void initializeGame
void makePlay (int player)
boolean endOfGame
void printWinner
AbstractGame
playOneGame
(int playerCount)
implements
Chess
void initializeGame
void makePlay(int player)
boolean endOfGame
void printWinner
implements
Redesign
Let’s use Strategy instead
Why would we do that?
Strategy Pattern
Create a template for the steps of an algorithm
and inject the specific functionality (strategy)
 Implement an interface to provide specific
functionality
– Algorithms can be selected on-the-fly at runtime
depending on conditions
– Similar as Template Method but uses interface
inheritance
Strategy Pattern
Game Strategy
Specific Game
implements
This is the generic
strategy of the game
play
This is the specific details
for this specific game
Design
interface
GameStrategy
void initializeGame
void makePlay (int player)
boolean endOfGame
void printWinner
GamePlay
GamaStrategy strategy
playOneGame (int playerCount)
ChessStrategy
void initializeGame
void makePlay(int player)
boolean endOfGame
void printWinner
implements
uses
The ChessStrategy
will be injected into
the game (context)
Assember
The Strategy
package is.ru.honn.game.framework;
public interface GameStrategy
{
public void initializeGame();
public void makePlay(int player);
public boolean endOfGame();
public void printWinner();
}
The Specific Strategy
class ChessStrategy implements GameStrategy
{
public void initializeGame()
{
// Initialize players, put the pieces on the board
}
public void makePlay(int player)
{
// Process a turn for the player
}
public boolean endOfGame()
{
// Return true if in Checkmate or stalemate
return true;
}
public void printWinner()
{
// Display the winning player
}
}
The Context
public class GamePlay
{
GameStrategy strategy;
protected int playersCount;
public void setStrategy(GameStrategy strategy)
{
this.strategy = strategy;
}
public final void playOneGame(int playersCount)
{
this.playersCount = playersCount;
this.strategy.initializeGame();
int j = 0;
while (!this.strategy.endOfGame()) {
this.strategy.makePlay(j);
j = (j + 1) % playersCount;
}
this.strategy.printWinner();
}
}
Polymorphism
The Assembler
GamePlay play = new GamePlay();
// Assign the right strategy
play.setStrategy(new ChessStrategy());
What design pattern is used
when the strategy is assigned
to the context?
Dependency Injection
Removes explicit dependence on specific
application code by injecting depending classes
into the framework
 Objects and interfaces are injected into the
classes that to the work
 Two types of injection
– Setter injection: using set methods
– Constructor injection: using constructors
Dependency Injection
Assembler
GamePlay play = new GamePlay()
play.setStrategy(new ChessStrategy())
ChessStrategy
initializeGame…
interface GameStrategy
initializeGame();
makePlay(int player);
endOfGame();
printWinner();
GamePlay
setStrategy(GameStrategy strategy)
playOneGame(int playersCount)
…
this.strategy.initializeGame();
create
implements
uses
Framework
create
Spring Framework
Lightweight Containers
 Assemble components from different projects
into a cohesive application
– Wiring is done with “Inversion of Control”
– Provide life-cycle management of objects
– Provide context
Overview
Spring 1 – Introduction
Lightweight Containers
 Manage objects
 Provide context
Spring Containers
 Lightweight containers
– Provides life-cycle management and other services
 BeanFactory
– Simple factory interface for creating beans
 ApplicationContext
– Extends BeanFactory and adds some functionality for
application context
 Packages
– org.springframework.beans
– org.springframework.context
– Refer to Spring 3
Spring Containers
 The concept
– Building applications from POJOs
Using BeanFactory
BeanFactory
<beans>
<bean id="person" class="Person">
<property name="name">
<value>Olafur Andri</value>
</property>
<property name="email">
<value>andri@ru.is</value>
</property>
</bean>
</beans>
read, parse
create
Person
The Bean Factory uses
setter injection to create the
person object
FileSystemXmlApplicationContext
 Loads the context from an XML file
 Application contexts are intended as central
registries
– Support of hierarchical contexts (nested)
public class AppTest
{
public static void main(String[] args)
{
ApplicationContext ctx =
new FileSystemXmlApplicationContext("app.xml");
}
}
Summary
 Framework patterns
– Inversion of Control and Dependency Injection
– Template Method
– Strategy
 From problems to patterns
– Game Framework
 Spring framework
– Bean containers
– BeanFactory and ApplicationContext

More Related Content

What's hot

J2EE vs JavaEE
J2EE vs JavaEEJ2EE vs JavaEE
J2EE vs JavaEE
eanimou
 
Model-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product LinesModel-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product Lines
Markus Voelter
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questions
ppratik86
 
Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal ApproachProject FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
Ivo Neskovic
 

What's hot (20)

Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of Patterns
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
Design pattern
Design patternDesign pattern
Design pattern
 
Ch08lect2 ud
Ch08lect2 udCh08lect2 ud
Ch08lect2 ud
 
J2EE vs JavaEE
J2EE vs JavaEEJ2EE vs JavaEE
J2EE vs JavaEE
 
Model-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product LinesModel-Driven Development in the context of Software Product Lines
Model-Driven Development in the context of Software Product Lines
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
 
Symfony Components
Symfony ComponentsSymfony Components
Symfony Components
 
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino DesignerAd103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
 
intellimeet
intellimeetintellimeet
intellimeet
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questions
 
Applet in java new
Applet in java newApplet in java new
Applet in java new
 
Poster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default MethodsPoster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default Methods
 
Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal ApproachProject FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Core java
Core javaCore java
Core java
 

Similar to L05 Frameworks

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Kumar
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 

Similar to L05 Frameworks (20)

Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
L5
L5L5
L5
 
Introduction To Design Patterns
Introduction To Design PatternsIntroduction To Design Patterns
Introduction To Design Patterns
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The World
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
L03 Design Patterns
L03 Design PatternsL03 Design Patterns
L03 Design Patterns
 
Lecture11
Lecture11Lecture11
Lecture11
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Spring boot
Spring bootSpring boot
Spring boot
 

More from Ólafur Andri Ragnarsson

L14 From the Internet to Blockchain
L14 From the Internet to BlockchainL14 From the Internet to Blockchain
L14 From the Internet to Blockchain
Ólafur Andri Ragnarsson
 
L12 digital transformation
L12 digital transformationL12 digital transformation
L12 digital transformation
Ólafur Andri Ragnarsson
 
L09 Technological Revolutions
L09 Technological RevolutionsL09 Technological Revolutions
L09 Technological Revolutions
Ó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

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
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
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

L05 Frameworks

  • 2. Agenda  Why frameworks?  Framework patterns – Inversion of Control and Dependency Injection – Template Method – Strategy  From problems to patterns – Game Framework  Spring framework – Bean containers – BeanFactory and ApplicationContext
  • 3. Reading  Dependency Injection  Template Method Pattern  Strategy Pattern  Spring Framework (video)  Article by Fowler – Inversion of Control Containers and the Dependency Injection pattern
  • 4. Resources  Spring Framework homepage – http://www.springframework.org  Reference Documentation – http://www.springframework.org/docs/reference/index. html – Also in PDF format
  • 6. Why use Frameworks?  Frameworks can increase productivity – We can create our own framework – We can use some third party framework  Frameworks implement general functionality – We use the framework to implement our business logic
  • 7. Framework design  Inheritance of framework classes  Composition of framework classes  Implementation of framework interfaces  Dependency Injection Framework Your Code Domain ?
  • 8. Using Frameworks  Frameworks are concrete, not abstract – Design patterns are conceptual, frameworks provide building blocks  Frameworks are higher-level – Built on design patterns  Frameworks are usually general or technology- specific  Good frameworks are simple to use, yet powerful
  • 9. Abstractions  From API to Frameworks API Definition JEE/.NET API API Patterns JEE/.NET Patterns Framework Spring
  • 10. Open Source Frameworks  Web Frameworks – Jakarta Struts, WebWork, Maverick, Play!  Database Frameworks – Hibernate, JDO, TopLink  General Framework – Spring, Expresso, PicoContainer, Avalon  Platform Frameworks – JEE
  • 11. Where do Frameworks Come From?  Who spends their time writing frameworks?  If they give them away, how can anyone make money?  Companies that use frameworks, have their developers work on them  Give the code, sell the training and consulting
  • 12. Write down the pros and cons (benefits and drawbacks) for frameworks. Use two columns, benefits on the left, drawbacks right EXERCISE
  • 13. Pros and Cons  Pros – Productivity – Well know application models and patterns – Tested functionality – Connection of different components – Use of open standards  Cons – Can be complicated, learning curve – Dependant on frameworks, difficult to change – Difficult to debug and find bugs – Performance problems can be difficult – Can be bought by an evil company
  • 15. Separation of Concerns  One of the main challenge of frameworks is to provide separation of concerns – Frameworks deal with generic functionality – Layers of code  Frameworks need patterns to combine generic and domain specific functionality
  • 16. Framework Patterns  Useful patterns when building a framework: – Dependency Injection: remove dependencies by injecting them (sometimes called Inversion of Control) – Template Method: extend a generic class and provide specific functionality – Strategy: Implement an interface to provide specific functionality
  • 17. Dependency Injection Removes explicit dependence on specific application code by injecting depending classes into the framework  Objects and interfaces are injected into the classes that to the work  Two types of injection – Setter injection: using set methods – Constructor injection: using constructors
  • 18. Dependency Injection  Fowler’s Naive Example – MovieLister uses a finder class – How can we separate the finder functionality? class MovieLister... public Movie[] moviesDirectedBy(String arg) { List allMovies = finder.findAll(); for (Iterator it = allMovies.iterator(); it.hasNext();) { Movie movie = (Movie) it.next(); if (!movie.getDirector().equals(arg)) it.remove(); } return (Movie[])allMovies.toArray(new Movie[allMovies.size()]); } Separate what varies REMEMBER PROGRAM TO INTERFACES PRINSIPLE?
  • 19. Dependency Injection  Fowler’s Naive Example – Let’s make an interface, MovieFinder – MovieLister is still dependent on particular MovieFinder implementation public interface MovieFinder { List findAll(); } class MovieLister... private MovieFinder finder; public MovieLister() { finder = new MovieFinderImpl("movies1.txt"); } Argh! Not cool.
  • 20. Dependency Injection  An assembler (or container) is used to create an implementation – Using constructor injection, the assember will create a MovieLister and passing a MovieFinder interface in the contructor – Using setter injection, the assembler will create MovieLister and then all the setFinder setter method to provide the MovieFinder interface
  • 21. Dependency Injection  Example setter injection class MovieLister... private MovieFinder finder; public void setFinder(MovieFinder finder) { this.finder = finder; } class MovieFinderImpl... public void setFilename(String filename) this.filename = filename; }
  • 23. Example  ContentLister public class ContentLister { private ContentFinder contentFinder; public void setContentFinder(ContentFinder contentFinder) { this.contentFinder = contentFinder; } public List<Content> find(String pattern) { return contentFinder.find(pattern); } }
  • 24. Example  ContentFinder interface public interface ContentFinder { List<Content> find(String pattern); }
  • 25. Example  SimpleContentFinder – implementation public class SimpleContentFinder implements ContentFinder { ... public List<Content> find(String pattern) { List<Content> contents = contentService.getContents(); List<Content> newList = new ArrayList<Content>(); for(Content c : contents) { if (c.getTitle().toLowerCase().contains(pattern)) { newList.add(c); } } return newList; } }
  • 26. Example  TestContentLister - Testcase public class TestContentLister extends TestCase { public void testContentLister () { ServiceFactoryserviceFactory = new ServiceFactory(); ContentServicecontentService = (ContentService) serviceFactory.getService("contentService"); contentService.addContent(new Content(1, "The Simpsons Movie", "", "", new Date() contentService.addContent(new Content(1, "The Bourne Ultimatum", "", "", new Date contentService.addContent(new Content(1, "Rush Hour 3", "", "", new Date(), "")); ContentFindercontentFinder = new SimpleContentFinder(contentService); ContentListercontentLister = new ContentLister(); contentLister.setContentFinder(contentFinder); List<Content>searchResults = contentLister.find("simpsons"); for (Content c : searchResults) { System.out.println(c); } } } Magic stuff
  • 28. Template Method Pattern Create a template for steps of an algorithm and let subclasses extend to provide specific functionality  We know the steps in an algorithm and the order – We don’t know specific functionality  How it works – Create an abstract superclass that can be extended for the specific functionality – Superclass will call the abstract methods when needed
  • 30. Template Method Pattern public class AbstractOrderEJB { public final Invoice placeOrder(int customerId, InvoiceItem[] items) throws NoSuchCustomerException, SpendingLimitViolation { int total = 0; for (int i=0; i < items.length; i++) { total += getItemPrice(items[i]) * items[i].getQuantity(); } if (total >getSpendingLimit(customerId)) { ... } else if (total > DISCOUNT_THRESHOLD) ... int invoiceId = placeOrder(customerId, total, items); ... } }
  • 31. Template Method Pattern AbstractOrderEJB placeOrder () abstract getItemPrice() abstract getSpendingLimit() abstract placeOrder() MyOrderEJB getItemPrice() getSpendingLimit() placeOrder() extends Domain specific functionality Generic functionality
  • 32. Template Method Pattern public class MyOrderEJB extends AbstractOrderEJB { ... int getItemPrice(int[] i) { ... } int getSpendingLimit(int customerId) { ... } int placeOrder(int customerId, int total, int items) { ... } }
  • 33. Template Method Pattern  When to Use it – For processes where steps are know but some steps need to be changed – Works if same team is doing the abstract and the concrete class  When Not to Use it – The concrete class is forced to inherit, limits possibilities – Developer of the concrete class must understand the abstract calls – If another team is doing the concrete class as this
  • 34. Strategy Pattern Create a template for the steps of an algorithm and inject the specific functionality  Implement an interface to provide specific functionality – Algorithms can be selected on-the-fly at runtime depending on conditions – Similar as Template Method but uses interface inheritance
  • 35. Strategy Pattern  How it works – Create an interface to use in the generic algorithm – Implementation of the interface provides the specific functionality – Framework class has reference to the interface an – Setter method for the interface
  • 37. Strategy Pattern  Interface for specific functionality  Generic class uses the interface – Set method to inject the interface public interface DataHelper { int getItemPrice(InvoiceItem item); int getSpendingLimit(CustomerId) throws NoSuchCustomerException; int palceOrder(int customerId, int total, InvoiceItem[] items); } private DataHelper dataHelper; public void setDataHelper(DataHelper newDataHelper) { this.dataHelper = newDataHelper; } DEPENDENCY INJECTION
  • 38. Strategy Pattern public class OrderEJB { public final Invoice placeOrder(int customerId, InvoiceItem[] items) throws NoSuchCustomerException, SpendingLimitViolation { int total = 0; for (int i=0; i < items.length; i++) { total += this.dataHelper.getItemPrice(items[i]) * items[i].getQuantity(); } if (total >this.dataHelper.getSpendingLimit(customerId)) {... } else if (total > DISCOUNT_THRESHOLD) ... int invoiceId = this.dataHelper.placeOrder(customerId, total, items); ... } }
  • 39. We are building framework for games. It turns out that all the games are similar so we create an abstract class for basic functionality that does not change, and then extend that class for each game. What pattern is this? A) Layered Supertype B) Template Method C) Strategy D) Dependency Injection QUIZ ✔
  • 40. From Problem to Patterns
  • 41. Framework design  Inheritance of framework classes Template Method – class Inheritance  Composition of framework classes Strategy – interface Inheritance Dependency Injection Framework Your Code Domain ?
  • 42. From Problem to Pattern We need to design game software Common turn-based board games like monopoly, chess, backgammon, yatzy etc. You must propose a design
  • 43. From Problem to Pattern Let’s make a Game Framework What patterns can we use?
  • 44. Patterns  Template Method – Template of an algorithm – Based on class inheritance  Strategy – Composition of an strategy – Based on interface inheritance
  • 45. Template Method Pattern Create a template for steps of an algorithm and let subclasses extend to provide specific functionality  We know the steps in an algorithm and the order – We don’t know specific functionality  How it works – Create an abstract superclass that can be extended for the specific functionality – Superclass will call the abstract methods when needed
  • 46. What is the game algorithm? initialize while more plays make one turn print winnner void initializeGame(); boolean endOfGame(); void makePlay(int player); void printWinner();
  • 47. Game Template Specific Game extends This is the generic template of the game play This is the specific details for this specific game
  • 48. Design interface Game void initializeGame void makePlay (int player) boolean endOfGame void printWinner AbstractGame playOneGame (int playerCount) implements Chess void initializeGame void makePlay(int player) boolean endOfGame void printWinner implements
  • 49. Interface for game algorithm package is.ru.honn.game.framework; public interface Game { public void initializeGame(); public void makePlay(int player); public boolean endOfGame(); public void printWinner(); }
  • 50. The Template package is.ru.honn.game.framework; public abstract class AbstractGame implements Game { protected int playersCount; public final void playOneGame(int playersCount) { this.playersCount = playersCount; initializeGame(); int j = 0; while (!endOfGame()) { makePlay(j); j = (j + 1) % playersCount; } printWinner(); } }
  • 51. The Specific Game class Chess extends AbstractGame { public void initializeGame() { // Initialize players, put the pieces on the board } public void makePlay(int player) { // Process a turn for the player } public boolean endOfGame() { // Return true if in Checkmate or stalemate return true; } public void printWinner() { // Display the winning player } }
  • 52. Design interface Game void initializeGame void makePlay (int player) boolean endOfGame void printWinner AbstractGame playOneGame (int playerCount) implements Chess void initializeGame void makePlay(int player) boolean endOfGame void printWinner implements
  • 53. Redesign Let’s use Strategy instead Why would we do that?
  • 54. Strategy Pattern Create a template for the steps of an algorithm and inject the specific functionality (strategy)  Implement an interface to provide specific functionality – Algorithms can be selected on-the-fly at runtime depending on conditions – Similar as Template Method but uses interface inheritance
  • 56. Game Strategy Specific Game implements This is the generic strategy of the game play This is the specific details for this specific game
  • 57. Design interface GameStrategy void initializeGame void makePlay (int player) boolean endOfGame void printWinner GamePlay GamaStrategy strategy playOneGame (int playerCount) ChessStrategy void initializeGame void makePlay(int player) boolean endOfGame void printWinner implements uses The ChessStrategy will be injected into the game (context) Assember
  • 58. The Strategy package is.ru.honn.game.framework; public interface GameStrategy { public void initializeGame(); public void makePlay(int player); public boolean endOfGame(); public void printWinner(); }
  • 59. The Specific Strategy class ChessStrategy implements GameStrategy { public void initializeGame() { // Initialize players, put the pieces on the board } public void makePlay(int player) { // Process a turn for the player } public boolean endOfGame() { // Return true if in Checkmate or stalemate return true; } public void printWinner() { // Display the winning player } }
  • 60. The Context public class GamePlay { GameStrategy strategy; protected int playersCount; public void setStrategy(GameStrategy strategy) { this.strategy = strategy; } public final void playOneGame(int playersCount) { this.playersCount = playersCount; this.strategy.initializeGame(); int j = 0; while (!this.strategy.endOfGame()) { this.strategy.makePlay(j); j = (j + 1) % playersCount; } this.strategy.printWinner(); } } Polymorphism
  • 61. The Assembler GamePlay play = new GamePlay(); // Assign the right strategy play.setStrategy(new ChessStrategy()); What design pattern is used when the strategy is assigned to the context?
  • 62. Dependency Injection Removes explicit dependence on specific application code by injecting depending classes into the framework  Objects and interfaces are injected into the classes that to the work  Two types of injection – Setter injection: using set methods – Constructor injection: using constructors
  • 63. Dependency Injection Assembler GamePlay play = new GamePlay() play.setStrategy(new ChessStrategy()) ChessStrategy initializeGame… interface GameStrategy initializeGame(); makePlay(int player); endOfGame(); printWinner(); GamePlay setStrategy(GameStrategy strategy) playOneGame(int playersCount) … this.strategy.initializeGame(); create implements uses Framework create
  • 65. Lightweight Containers  Assemble components from different projects into a cohesive application – Wiring is done with “Inversion of Control” – Provide life-cycle management of objects – Provide context
  • 66. Overview Spring 1 – Introduction
  • 67. Lightweight Containers  Manage objects  Provide context
  • 68. Spring Containers  Lightweight containers – Provides life-cycle management and other services  BeanFactory – Simple factory interface for creating beans  ApplicationContext – Extends BeanFactory and adds some functionality for application context  Packages – org.springframework.beans – org.springframework.context – Refer to Spring 3
  • 69. Spring Containers  The concept – Building applications from POJOs
  • 70. Using BeanFactory BeanFactory <beans> <bean id="person" class="Person"> <property name="name"> <value>Olafur Andri</value> </property> <property name="email"> <value>andri@ru.is</value> </property> </bean> </beans> read, parse create Person The Bean Factory uses setter injection to create the person object
  • 71. FileSystemXmlApplicationContext  Loads the context from an XML file  Application contexts are intended as central registries – Support of hierarchical contexts (nested) public class AppTest { public static void main(String[] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext("app.xml"); } }
  • 72. Summary  Framework patterns – Inversion of Control and Dependency Injection – Template Method – Strategy  From problems to patterns – Game Framework  Spring framework – Bean containers – BeanFactory and ApplicationContext