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