SlideShare a Scribd company logo
1 of 33
Download to read offline
HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015
L08 USING FRAMEWORKS
Agenda
From Problem to Patterns
Implementing a simple game
Template Method
Strategy
Dependency Injection
Dependency Injection
Template Method Pattern
Strategy Pattern
Spring Framework (video)
Article by Fowler
Inversion of Control Containers and the
Dependency Injection pattern
Reading
From Problems to Patterns
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
Let’s make a Game TicTacToe
Let’s make a Game Framework
What patterns can we use?
From Problem to Patterns
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
interface 	
  
Game	
  
void initializeGame();
boolean endOfGame();
void makePlay(int player);
void printWinner();
void playOneGame();
void setPlayersCount(int playerCount);
AbstractGame
void playOneGame();
void setPlayersCount(int playerCount);
implements
TicTacToe	
  
void initializeGame
void makePlay(int player)
boolean endOfGame
void printWinner
extends
Design
Interface for game algorithm
package is.ru.honn.game.framwork;



public interface Game

{

void setPlayersCount(int playerCount);

void initializeGame();

void makePlay(int player);

boolean endOfGame();

void printWinner();

void playOneGame();

}

package is.ru.honn.game.framwork;
public abstract class AbstractGame implements Game
{
protected int playersCount;
public void setPlayersCount(int playersCount)
{
this.playersCount = playersCount;
}
public abstract void initializeGame();
public abstract void makePlay(int player);
public abstract boolean endOfGame();
public abstract void printWinner();
public final void playOneGame()
{
initializeGame();
int j = 0;
while (!endOfGame())
{
makePlay(j);
j = (j + 1) % playersCount;
}
The Template
DEPENDENCY INJECTION
GAMES MUST DO THIS
public final void playOneGame()
{
initializeGame();
int j = 0;
while (!endOfGame())
{
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
The Template
GAME LOOP
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class GameRunner
{
public static void main(String[] args)
{
ApplicationContext context= new
ClassPathXmlApplicationContext("/spring-config.xml");
Game game = (Game)context.getBean("game");
game.playOneGame();
}
}
Game Runner
DEPENDENCY INJECTION
PLUGIN PATTERN
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://
www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="game" class="is.ru.honn.game.tictactoe.TicTacToeGame">
<property name="playersCount">
<value>2</value>
</property>
</bean>
</beans>
The Template
public class TicTacToeGame extends AbstractGame
{
private char[][] board;
private final int[][] MARK = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
private char currentPlayerMark;
public void initializeGame()
{
board = new char[3][3];
currentPlayerMark = 'X';
initializeBoard();
printBoard();
System.out.println("To play, enter the number");
System.out.println("123n456n789non the board.");
}
The TicTacToe Game
public void makePlay(int player)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Player " + currentPlayerMark + " move: ");
int mark = 0;
try
{
String s = br.readLine();
mark = Integer.valueOf(s);
}
catch (IOException e)
{
e.printStackTrace();
}
board[col(mark)][row(mark)] = currentPlayerMark;
changePlayer();
printBoard();
}
The TicTacToe Game
public boolean endOfGame()
{
return (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin());
}
public void printWinner()
{
changePlayer();
System.out.println("Winner is " + currentPlayerMark);
}
The TicTacToe Game
interface 	
  
Game	
  
void initializeGame();
boolean endOfGame();
void makePlay(int player);
void printWinner();
void playOneGame();
void setPlayersCount(int playerCount);
AbstractGame
void playOneGame();
void setPlayersCount(int playerCount);
implements
TicTacToe	
  
void initializeGame
void makePlay(int player)
boolean endOfGame
void printWinner
extends
Design
Redesgin
Let’s use strategy instead
Why would we do that?
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
Game	
  Strategy
Specific	
  Game
Implements
This	
  is	
  the	
  generic
template	
  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();

int getPlayersCount();
GamePlay
GamaStrategy strategy
setGameStrategy(GameStrategy g)
playOneGame (int playerCount)
TicTacToeStrategy
void initializeGame();

void makePlay(int player);

boolean endOfGame();

void printWinner();

int getPlayersCount();
implements
uses
The ChessStrategy

will be injected into
the game (context)
GameRunner
The Strategy
package is.ru.honn.game.framwork;
public interface GameStrategy
{
void initializeGame();
void makePlay(int player);
boolean endOfGame();
void printWinner();
int getPlayersCount();
}
The Specific Strategy
public class TicTacToeStrategy implements GameStrategy

{

private char[][] board;

private final int[][] MARK = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

private char currentPlayerMark;

protected int playersCount;



public void setPlayersCount(int playersCount)

{ this.playersCount = playersCount; }



public int getPlayersCount()

{ return playersCount; }



public void initializeGame()

{

board = new char[3][3];

currentPlayerMark = 'X';

initializeBoard();

printBoard();

System.out.println("To play, enter the number");

System.out.println("123n456n789non the board.");

}
The Context
package is.ru.honn.game.framwork;
public class GamePlay
{
protected int playersCount;
protected GameStrategy gameStrategy;
public void setGameStrategy(GameStrategy gameStrategy)
{ this.gameStrategy = gameStrategy; }
public final void playOneGame(int playersCount)
{
gameStrategy.initializeGame();
int j = 0;
while (!gameStrategy.endOfGame())
{
gameStrategy.makePlay(j);
j = (j + 1) % playersCount;
}
gameStrategy.printWinner();
}
}
DEPENDENCY INJECTION
The Assembler
package is.ru.honn.game.framwork;



import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;



public class GameRunner

{

public static void main(String[] args)

{

ApplicationContext context= new

ClassPathXmlApplicationContext("/spring-config.xml");

GameStrategy game = (GameStrategy)context.getBean("game");



GamePlay play = new GamePlay();

play.setGameStrategy(game);



play.playOneGame(game.getPlayersCount());



}

}

DEPENDENCY INJECTION
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
Next
Process Design

More Related Content

Similar to L08 Using Frameworks

Data Driven Game development
Data Driven Game developmentData Driven Game development
Data Driven Game developmentKostas Anagnostou
 
Making a game "Just Right" through testing and play balancing
Making a game "Just Right" through testing and play balancingMaking a game "Just Right" through testing and play balancing
Making a game "Just Right" through testing and play balancingJulio Gorgé
 
Introduction to html5 game programming with impact js
Introduction to html5 game programming with impact jsIntroduction to html5 game programming with impact js
Introduction to html5 game programming with impact jsLuca Galli
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeScott Wlaschin
 
Game Development Session - 3 | Introduction to Unity
Game Development Session - 3 | Introduction to  UnityGame Development Session - 3 | Introduction to  Unity
Game Development Session - 3 | Introduction to UnityKoderunners
 
Playoff how to create a game
Playoff how to create a gamePlayoff how to create a game
Playoff how to create a gameSilvia Galessi
 
Using FireMonkey as a game engine
Using FireMonkey as a game engineUsing FireMonkey as a game engine
Using FireMonkey as a game enginepprem
 
Game Development With Python and Pygame
Game Development With Python and PygameGame Development With Python and Pygame
Game Development With Python and PygameChariza Pladin
 
Java term project final report
Java term project final reportJava term project final report
Java term project final reportJiwon Han
 
How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?Flutter Agency
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfudit652068
 
Rapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjectsRapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjectsGiorgio Pomettini
 
Engine terminology
Engine terminologyEngine terminology
Engine terminologythomasmcd6
 
Tools for developing Android Games
 Tools for developing Android Games Tools for developing Android Games
Tools for developing Android GamesPlatty Soft
 
Jake hyatt Y1 gd engine_terminology
Jake hyatt Y1 gd engine_terminologyJake hyatt Y1 gd engine_terminology
Jake hyatt Y1 gd engine_terminologyJakeyhyatt123
 
TAZ ActionTrack - Collaboration offer to edu companies v2
TAZ ActionTrack - Collaboration offer to edu companies v2TAZ ActionTrack - Collaboration offer to edu companies v2
TAZ ActionTrack - Collaboration offer to edu companies v2Kari Laurila
 

Similar to L08 Using Frameworks (20)

Data Driven Game development
Data Driven Game developmentData Driven Game development
Data Driven Game development
 
Ubiquitous Language
Ubiquitous LanguageUbiquitous Language
Ubiquitous Language
 
Making a game "Just Right" through testing and play balancing
Making a game "Just Right" through testing and play balancingMaking a game "Just Right" through testing and play balancing
Making a game "Just Right" through testing and play balancing
 
Introduction to html5 game programming with impact js
Introduction to html5 game programming with impact jsIntroduction to html5 game programming with impact js
Introduction to html5 game programming with impact js
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-Toe
 
Unity3D Programming
Unity3D ProgrammingUnity3D Programming
Unity3D Programming
 
Game Development Session - 3 | Introduction to Unity
Game Development Session - 3 | Introduction to  UnityGame Development Session - 3 | Introduction to  Unity
Game Development Session - 3 | Introduction to Unity
 
Playoff how to create a game
Playoff how to create a gamePlayoff how to create a game
Playoff how to create a game
 
Unity workshop
Unity workshopUnity workshop
Unity workshop
 
Using FireMonkey as a game engine
Using FireMonkey as a game engineUsing FireMonkey as a game engine
Using FireMonkey as a game engine
 
Pong
PongPong
Pong
 
Game Development With Python and Pygame
Game Development With Python and PygameGame Development With Python and Pygame
Game Development With Python and Pygame
 
Java term project final report
Java term project final reportJava term project final report
Java term project final report
 
How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
 
Rapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjectsRapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjects
 
Engine terminology
Engine terminologyEngine terminology
Engine terminology
 
Tools for developing Android Games
 Tools for developing Android Games Tools for developing Android Games
Tools for developing Android Games
 
Jake hyatt Y1 gd engine_terminology
Jake hyatt Y1 gd engine_terminologyJake hyatt Y1 gd engine_terminology
Jake hyatt Y1 gd engine_terminology
 
TAZ ActionTrack - Collaboration offer to edu companies v2
TAZ ActionTrack - Collaboration offer to edu companies v2TAZ ActionTrack - Collaboration offer to edu companies v2
TAZ ActionTrack - Collaboration offer to edu companies v2
 

More from Ólafur Andri Ragnarsson

New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionÓlafur Andri Ragnarsson
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine Ólafur Andri Ragnarsson
 

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

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
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...ICS
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Recently uploaded (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
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...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

L08 Using Frameworks

  • 1. HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015 L08 USING FRAMEWORKS
  • 2. Agenda From Problem to Patterns Implementing a simple game Template Method Strategy Dependency Injection
  • 3. Dependency Injection Template Method Pattern Strategy Pattern Spring Framework (video) Article by Fowler Inversion of Control Containers and the Dependency Injection pattern Reading
  • 4. From Problems to Patterns
  • 5. 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
  • 6. Framework design ▪ Inheritance of framework classes ▪ Composition of framework classes ▪ Implementation of framework interfaces ▪ Dependency Injection ?Your Domain Code Framework
  • 7. Let’s make a Game TicTacToe Let’s make a Game Framework What patterns can we use? From Problem to Patterns
  • 8. Patterns ▪ Template Method – Template of an algorithm – Based on class inheritance ▪ Strategy – Composition of an strategy – Based on interface inheritance
  • 9. 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
  • 10. What is the game algorithm? initialize while more plays make one turn print winnner void initializeGame(); boolean endOfGame(); void makePlay(int player); void printWinner();
  • 11. Game  Template Specific  Game extends This  is  the  generic template  of  the  game   play   This  is  the  specific  details
 for  this  specific  game
  • 12. interface   Game   void initializeGame(); boolean endOfGame(); void makePlay(int player); void printWinner(); void playOneGame(); void setPlayersCount(int playerCount); AbstractGame void playOneGame(); void setPlayersCount(int playerCount); implements TicTacToe   void initializeGame void makePlay(int player) boolean endOfGame void printWinner extends Design
  • 13. Interface for game algorithm package is.ru.honn.game.framwork;
 
 public interface Game
 {
 void setPlayersCount(int playerCount);
 void initializeGame();
 void makePlay(int player);
 boolean endOfGame();
 void printWinner();
 void playOneGame();
 }

  • 14. package is.ru.honn.game.framwork; public abstract class AbstractGame implements Game { protected int playersCount; public void setPlayersCount(int playersCount) { this.playersCount = playersCount; } public abstract void initializeGame(); public abstract void makePlay(int player); public abstract boolean endOfGame(); public abstract void printWinner(); public final void playOneGame() { initializeGame(); int j = 0; while (!endOfGame()) { makePlay(j); j = (j + 1) % playersCount; } The Template DEPENDENCY INJECTION GAMES MUST DO THIS
  • 15. public final void playOneGame() { initializeGame(); int j = 0; while (!endOfGame()) { makePlay(j); j = (j + 1) % playersCount; } printWinner(); } } The Template GAME LOOP
  • 16. import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class GameRunner { public static void main(String[] args) { ApplicationContext context= new ClassPathXmlApplicationContext("/spring-config.xml"); Game game = (Game)context.getBean("game"); game.playOneGame(); } } Game Runner DEPENDENCY INJECTION PLUGIN PATTERN
  • 17. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http:// www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="game" class="is.ru.honn.game.tictactoe.TicTacToeGame"> <property name="playersCount"> <value>2</value> </property> </bean> </beans> The Template
  • 18. public class TicTacToeGame extends AbstractGame { private char[][] board; private final int[][] MARK = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; private char currentPlayerMark; public void initializeGame() { board = new char[3][3]; currentPlayerMark = 'X'; initializeBoard(); printBoard(); System.out.println("To play, enter the number"); System.out.println("123n456n789non the board."); } The TicTacToe Game
  • 19. public void makePlay(int player) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Player " + currentPlayerMark + " move: "); int mark = 0; try { String s = br.readLine(); mark = Integer.valueOf(s); } catch (IOException e) { e.printStackTrace(); } board[col(mark)][row(mark)] = currentPlayerMark; changePlayer(); printBoard(); } The TicTacToe Game
  • 20. public boolean endOfGame() { return (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin()); } public void printWinner() { changePlayer(); System.out.println("Winner is " + currentPlayerMark); } The TicTacToe Game
  • 21. interface   Game   void initializeGame(); boolean endOfGame(); void makePlay(int player); void printWinner(); void playOneGame(); void setPlayersCount(int playerCount); AbstractGame void playOneGame(); void setPlayersCount(int playerCount); implements TicTacToe   void initializeGame void makePlay(int player) boolean endOfGame void printWinner extends Design
  • 22. Redesgin Let’s use strategy instead Why would we do that?
  • 23. 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
  • 24. 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
  • 26. Game  Strategy Specific  Game Implements This  is  the  generic template  of  the  game   play   This  is  the  specific  details
 for  this  specific  game
  • 27. Design interface   GameStrategy void initializeGame();
 void makePlay(int player);
 boolean endOfGame();
 void printWinner();
 int getPlayersCount(); GamePlay GamaStrategy strategy setGameStrategy(GameStrategy g) playOneGame (int playerCount) TicTacToeStrategy void initializeGame();
 void makePlay(int player);
 boolean endOfGame();
 void printWinner();
 int getPlayersCount(); implements uses The ChessStrategy
 will be injected into the game (context) GameRunner
  • 28. The Strategy package is.ru.honn.game.framwork; public interface GameStrategy { void initializeGame(); void makePlay(int player); boolean endOfGame(); void printWinner(); int getPlayersCount(); }
  • 29. The Specific Strategy public class TicTacToeStrategy implements GameStrategy
 {
 private char[][] board;
 private final int[][] MARK = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
 private char currentPlayerMark;
 protected int playersCount;
 
 public void setPlayersCount(int playersCount)
 { this.playersCount = playersCount; }
 
 public int getPlayersCount()
 { return playersCount; }
 
 public void initializeGame()
 {
 board = new char[3][3];
 currentPlayerMark = 'X';
 initializeBoard();
 printBoard();
 System.out.println("To play, enter the number");
 System.out.println("123n456n789non the board.");
 }
  • 30. The Context package is.ru.honn.game.framwork; public class GamePlay { protected int playersCount; protected GameStrategy gameStrategy; public void setGameStrategy(GameStrategy gameStrategy) { this.gameStrategy = gameStrategy; } public final void playOneGame(int playersCount) { gameStrategy.initializeGame(); int j = 0; while (!gameStrategy.endOfGame()) { gameStrategy.makePlay(j); j = (j + 1) % playersCount; } gameStrategy.printWinner(); } } DEPENDENCY INJECTION
  • 31. The Assembler package is.ru.honn.game.framwork;
 
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 public class GameRunner
 {
 public static void main(String[] args)
 {
 ApplicationContext context= new
 ClassPathXmlApplicationContext("/spring-config.xml");
 GameStrategy game = (GameStrategy)context.getBean("game");
 
 GamePlay play = new GamePlay();
 play.setGameStrategy(game);
 
 play.playOneGame(game.getPlayersCount());
 
 }
 }
 DEPENDENCY INJECTION
  • 32. 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