L05 Frameworks

72
Lecture 05 Frameworks

description

Frameworks are general code libraries that developers use to build their software on. Frameworks are usually specific to a domain, like web frameworks or database frameworks. The benefit of frameworks is the productivity that they provide. With the right framework we can avoid writing low-level functionality and instead focus on our domain problems we need to solve. Frameworks are building blocks and should be used as such, if you have a bad framework or need to invest too much into using the framework, the gains are counter productive. It may be a good strategy to write your own framework, and in the lecture we look at design patterns that are useful in creating frameworks. We will also look at the Spring framework that is a good example of a well design framework. Cover image by Javier Corbo http://www.flickr.com/photos/javiercorbo/

Transcript of L05 Frameworks

Page 1: L05 Frameworks

Lecture 05Frameworks

Page 2: L05 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

Page 3: L05 Frameworks

Reading Dependency Injection Template Method Pattern Strategy Pattern Spring Framework (video) Article by Fowler

– Inversion of Control Containers and the Dependency Injection pattern

Page 4: L05 Frameworks

Resources Spring Framework homepage

– http://www.springframework.org Reference Documentation

– http://www.springframework.org/docs/reference/index.html

– Also in PDF format

Page 5: L05 Frameworks

Why Frameworks?

Page 6: L05 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

Page 7: L05 Frameworks

Framework design Inheritance of framework classes Composition of framework classes Implementation of framework interfaces Dependency Injection

FrameworkYour CodeDomain ?

Page 8: L05 Frameworks

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

Page 9: L05 Frameworks

Abstractions From API to Frameworks

API Definition JEE/.NET API

API Patterns JEE/.NETPatterns

Framework Spring

Page 10: L05 Frameworks

Open Source Frameworks Web Frameworks

– Jakarta Struts, WebWork, Maverick, Play! Database Frameworks

– Hibernate, JDO, TopLink General Framework

– Spring, Expresso, PicoContainer, Avalon Platform Frameworks

– JEE

Page 11: L05 Frameworks

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

Page 12: L05 Frameworks

Write down the pros and cons (benefits and drawbacks) for frameworks.Use two columns, benefits on the left, drawbacks right

EXERCISE

Page 13: L05 Frameworks

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

Page 14: L05 Frameworks

Framework Patterns

Page 15: L05 Frameworks

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

Page 16: L05 Frameworks

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

Page 17: L05 Frameworks

Dependency InjectionRemoves 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

Page 18: L05 Frameworks

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?

Page 19: L05 Frameworks

Dependency Injection Fowler’s Naive Example

– Let’s make an interface, MovieFinder– MovieLister is still dependent on particular

MovieFinder implementationpublic interface MovieFinder { List findAll();}

class MovieLister... private MovieFinder finder; public MovieLister() { finder = new MovieFinderImpl("movies1.txt"); }

Argh!Not cool.

Page 20: L05 Frameworks

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 createMovieLister and then all the setFinder setter method to provide theMovieFinder interface

Page 21: L05 Frameworks

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; }

Page 22: L05 Frameworks

Dependency Injection

SEPARATED INTERFACE

Page 23: L05 Frameworks

Example ContentListerpublic class ContentLister{ private ContentFinder contentFinder;

public void setContentFinder(ContentFinder contentFinder) { this.contentFinder = contentFinder; }

public List<Content> find(String pattern) { return contentFinder.find(pattern); }}

Page 24: L05 Frameworks

Example ContentFinder interface

public interface ContentFinder{ List<Content> find(String pattern);}

Page 25: L05 Frameworks

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; }}

Page 26: L05 Frameworks

Example TestContentLister - Testcasepublic 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

Page 27: L05 Frameworks

Example

Page 28: L05 Frameworks

Template Method PatternCreate 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

Page 29: L05 Frameworks

Template Method Pattern

Page 30: L05 Frameworks

Template Method Patternpublic 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); ... }}

Page 31: L05 Frameworks

Template Method Pattern

AbstractOrderEJBplaceOrder ()

abstract getItemPrice()abstract getSpendingLimit()

abstract placeOrder()

MyOrderEJBgetItemPrice()

getSpendingLimit()placeOrder()

extends

Domainspecificfunctionality

Genericfunctionality

Page 32: L05 Frameworks

Template Method Patternpublic class MyOrderEJB extends AbstractOrderEJB{ ... int getItemPrice(int[] i) { ... }

int getSpendingLimit(int customerId) { ... }

int placeOrder(int customerId, int total, int items) { ... }}

Page 33: L05 Frameworks

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

Page 34: L05 Frameworks

Strategy PatternCreate 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

Page 35: L05 Frameworks

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

Page 36: L05 Frameworks

Strategy Pattern

Page 37: L05 Frameworks

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

Page 38: L05 Frameworks

Strategy Patternpublic 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); ... }}

Page 39: L05 Frameworks

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 SupertypeB) Template MethodC) StrategyD) Dependency Injection

QUIZ

Page 40: L05 Frameworks

From Problem to Patterns

Page 41: L05 Frameworks

Framework design Inheritance of framework classes

Template Method – class Inheritance Composition of framework classes

Strategy – interface InheritanceDependency Injection

FrameworkYour CodeDomain ?

Page 42: L05 Frameworks

From Problem to PatternWe need to design game software

Common turn-based board games like monopoly, chess, backgammon, yatzy etc.

You must propose a design

Page 43: L05 Frameworks

From Problem to PatternLet’s make a Game Framework

What patterns can we use?

Page 44: L05 Frameworks

Patterns Template Method

– Template of an algorithm– Based on class inheritance

Strategy– Composition of an strategy– Based on interface inheritance

Page 45: L05 Frameworks

Template Method PatternCreate 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

Page 46: L05 Frameworks

What is the game algorithm?

initialize

while more playsmake one turn

print winnner

void initializeGame();

boolean endOfGame();

void makePlay(int player);

void printWinner();

Page 47: L05 Frameworks

Game Template

Specific Game

extends

This is the generictemplate of the game play

This is the specific detailsfor this specific game

Page 48: L05 Frameworks

Design

interface Game

void initializeGamevoid makePlay (int player)boolean endOfGamevoid printWinner

AbstractGame

playOneGame (int playerCount)

imp

lem

ents

Chess

void initializeGamevoid makePlay(int player)boolean endOfGamevoid printWinner

implements

Page 49: L05 Frameworks

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();}

Page 50: L05 Frameworks

The Templatepackage 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(); }}

Page 51: L05 Frameworks

The Specific Gameclass 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 }}

Page 52: L05 Frameworks

Design

interface Game

void initializeGamevoid makePlay (int player)boolean endOfGamevoid printWinner

AbstractGame

playOneGame (int playerCount)

imp

lem

ents

Chess

void initializeGamevoid makePlay(int player)boolean endOfGamevoid printWinner

implements

Page 53: L05 Frameworks

RedesignLet’s use Strategy instead

Why would we do that?

Page 54: L05 Frameworks

Strategy PatternCreate 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

Page 55: L05 Frameworks

Strategy Pattern

Page 56: L05 Frameworks

Game Strategy

Specific Game

implements

This is the genericstrategy of the game play

This is the specific detailsfor this specific game

Page 57: L05 Frameworks

Design

interfaceGameStrategy

void initializeGamevoid makePlay (int player)boolean endOfGamevoid printWinner

GamePlay

GamaStrategy strategy

playOneGame (int playerCount)

ChessStrategy

void initializeGamevoid makePlay(int player)boolean endOfGamevoid printWinner

implements

uses

The ChessStrategywill be injected into the game (context)

Assember

Page 58: L05 Frameworks

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();}

Page 59: L05 Frameworks

The Specific Strategyclass 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 }}

Page 60: L05 Frameworks

The Contextpublic 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

Page 61: L05 Frameworks

The Assembler

GamePlay play = new GamePlay(); // Assign the right strategyplay.setStrategy(new ChessStrategy());

What design pattern is used when the strategy is assigned to the context?

Page 62: L05 Frameworks

Dependency InjectionRemoves 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

Page 63: L05 Frameworks

Dependency InjectionAssembler

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();

createimplements

uses

Framework

create

Page 64: L05 Frameworks

Spring Framework

Page 65: L05 Frameworks

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

Page 66: L05 Frameworks

Overview

Spring 1 – Introduction

Page 67: L05 Frameworks

Lightweight Containers Manage objects Provide context

Page 68: L05 Frameworks

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

Page 69: L05 Frameworks

Spring Containers The concept

– Building applications from POJOs

Page 70: L05 Frameworks

Using BeanFactory

BeanFactory

<beans> <bean id="person" class="Person"> <property name="name"> <value>Olafur Andri</value> </property> <property name="email"> <value>[email protected]</value> </property> </bean></beans>

read, parse

create

PersonThe Bean Factory usessetter injection to create theperson object

Page 71: L05 Frameworks

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"); }}

Page 72: L05 Frameworks

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