SlideShare a Scribd company logo
1 of 51
Download to read offline
HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015
L07 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
?Your
Domain Code
Framework
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
The Hollywood Principle
▪ “Don’t call us, we’ll call you”
▪ Your program does not call the framework, it’s the framework
that controls the execution of your program
TRADITIONAL HOLLYWOOD CALL
Framework
Handler Handler
Framework
Program Program
Inversion of Control (IoC)
▪ Your application runs in a container (framework)
▪ Container manages the life-cycle of your object and provides
context
▪ The framework has the control
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
▪ 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()]);
}
REMEMBER PROGRAM TO INTERFACES PRINCIPLE?
Dependency Injection
Separate	
  what	
  varies
▪ 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 assembler will create a
MovieLister and passing a MovieFinder interface in the
contractor
– 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
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 hundred-foot Journey", "", "", new Dat
contentService.addContent(new Content(1, ”Life of Crime", "", "", new Date(), ""));
contentService.addContent(new Content(1, ”The November Man", "", "", 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
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 creates
too much communication load between teams
Template Method 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
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) Layer Supertype
B) Template Method
C) Strategy
D) Dependency Injection
QUIZ
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
✔
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

Spring AOP Introduction
Spring AOP IntroductionSpring AOP Introduction
Spring AOP Introduction
b0ris_1
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management tool
Renato Primavera
 

What's hot (20)

9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Session 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationSession 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate Integration
 
Spring aop
Spring aopSpring aop
Spring aop
 
Spring AOP Introduction
Spring AOP IntroductionSpring AOP Introduction
Spring AOP Introduction
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch10
9781337102087 ppt ch109781337102087 ppt ch10
9781337102087 ppt ch10
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
 
Spring framework part 2
Spring framework  part 2Spring framework  part 2
Spring framework part 2
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration
 
Testing Spring MVC and REST Web Applications
Testing Spring MVC and REST Web ApplicationsTesting Spring MVC and REST Web Applications
Testing Spring MVC and REST Web Applications
 
Architectural Design Pattern: Android
Architectural Design Pattern: AndroidArchitectural Design Pattern: Android
Architectural Design Pattern: Android
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Struts2
Struts2Struts2
Struts2
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management tool
 
intellimeet
intellimeetintellimeet
intellimeet
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
Ee java lab assignment 4
Ee java lab assignment 4Ee java lab assignment 4
Ee java lab assignment 4
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 

Viewers also liked (14)

L09 Process Design
L09 Process DesignL09 Process Design
L09 Process Design
 
L08 Unit Testing
L08 Unit TestingL08 Unit Testing
L08 Unit Testing
 
L12 Visualizing Architecture
L12 Visualizing ArchitectureL12 Visualizing Architecture
L12 Visualizing Architecture
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
L11 Service Design and REST
L11 Service Design and RESTL11 Service Design and REST
L11 Service Design and REST
 
L16 Documenting Software
L16 Documenting SoftwareL16 Documenting Software
L16 Documenting Software
 
L17 Data Source Layer
L17 Data Source LayerL17 Data Source Layer
L17 Data Source Layer
 
L15 Organising Domain Layer
L15 Organising Domain LayerL15 Organising Domain Layer
L15 Organising Domain Layer
 
L18 Object Relational Mapping
L18 Object Relational MappingL18 Object Relational Mapping
L18 Object Relational Mapping
 
L10 Architecture Considerations
L10 Architecture ConsiderationsL10 Architecture Considerations
L10 Architecture Considerations
 
L21 Architecture and Agile
L21 Architecture and AgileL21 Architecture and Agile
L21 Architecture and Agile
 
L20 Scalability
L20 ScalabilityL20 Scalability
L20 Scalability
 
L19 Application Architecture
L19 Application ArchitectureL19 Application Architecture
L19 Application Architecture
 
Commercial track 2_UDP Solution Selling Made Simple
Commercial track 2_UDP Solution Selling Made SimpleCommercial track 2_UDP Solution Selling Made Simple
Commercial track 2_UDP Solution Selling Made Simple
 

Similar to L07 Frameworks

Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvpZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
Chalermpon Areepong
 

Similar to L07 Frameworks (20)

L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandt
 
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
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
Creating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJSCreating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJS
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
Sitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helixSitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helix
 
Diving Into Xamarin.Forms
Diving Into Xamarin.Forms Diving Into Xamarin.Forms
Diving Into Xamarin.Forms
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
BMO - Intelligent Projects with Maven
BMO - Intelligent Projects with MavenBMO - Intelligent Projects with Maven
BMO - Intelligent Projects with Maven
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncube
 
Spring boot
Spring bootSpring boot
Spring boot
 
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvpZZ BC#7 asp.net mvc practice and guideline by NineMvp
ZZ BC#7 asp.net mvc practice and guideline by NineMvp
 

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

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

L07 Frameworks

  • 1. HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015 L07 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 ?Your Domain Code Framework
  • 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. The Hollywood Principle ▪ “Don’t call us, we’ll call you” ▪ Your program does not call the framework, it’s the framework that controls the execution of your program TRADITIONAL HOLLYWOOD CALL Framework Handler Handler Framework Program Program
  • 17. Inversion of Control (IoC) ▪ Your application runs in a container (framework) ▪ Container manages the life-cycle of your object and provides context ▪ The framework has the control
  • 18. 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
  • 19. 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
  • 20. ▪ 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()]); } REMEMBER PROGRAM TO INTERFACES PRINCIPLE? Dependency Injection Separate  what  varies
  • 21. ▪ 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
  • 22. ▪ An assembler (or container) is used to create an implementation – Using constructor injection, the assembler will create a MovieLister and passing a MovieFinder interface in the contractor – Using setter injection, the assembler will create
 MovieLister and then all the setFinder setter 
 method to provide the
 MovieFinder interface Dependency Injection
  • 23. ▪ 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
  • 25. 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); } }
  • 26. Example ▪ ContentFinder interface public interface ContentFinder { List<Content> find(String pattern); }
  • 27. 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; } }
  • 28. 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 hundred-foot Journey", "", "", new Dat contentService.addContent(new Content(1, ”Life of Crime", "", "", new Date(), "")); contentService.addContent(new Content(1, ”The November Man", "", "", 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
  • 30. 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
  • 32. 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); ... } }
  • 33. Template Method Pattern AbstractOrderEJB placeOrder () abstract getItemPrice() abstract getSpendingLimit() abstract placeOrder() MyOrderEJB getItemPrice() getSpendingLimit() placeOrder() extends Domain specific functionality Generic functionality
  • 34. public class MyOrderEJB extends AbstractOrderEJB { ... int getItemPrice(int[] i) { ... } int getSpendingLimit(int customerId) { ... } int placeOrder(int customerId, int total, int items) { ... } } Template Method Pattern
  • 35. ▪ 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 creates too much communication load between teams Template Method Pattern
  • 36. 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
  • 37. 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
  • 39. 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
  • 40. 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); ... } }
  • 41. 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) Layer Supertype B) Template Method C) Strategy D) Dependency Injection QUIZ
  • 42. 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 ✔
  • 44. 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
  • 45. Overview Spring 1 – Introduction
  • 46. Lightweight Containers ▪ Manage objects ▪ Provide context
  • 47. 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
  • 48. Spring Containers ▪ The concept – Building applications from POJOs
  • 49. 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
  • 50. 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"); } }
  • 51. 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