patrons de conception (design patterns)blansche/files/ogl_cours_5.pdf · introduction cr´eation...

120
Introduction Cr´ eation Structure Comportement Patrons de conception (Design patterns) Outils de g´ enie logiciel 28 avril 2009 1 / 18

Upload: vongoc

Post on 25-Apr-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

Introduction Creation Structure Comportement

Patrons de conception (Design patterns)

Outils de genie logiciel

28 avril 2009

1 / 18

Introduction Creation Structure Comportement

Design pattern

◮ Design Patterns – Elements of Reusable Object-Oriented

Software, Erich Gamma, Richard Helm, Ralph Johnson etJohn Vlissides

◮ En francais : patrons/formes/motifs de conception

◮ Inspire des methodes de conception en architecture

2 / 18

Introduction Creation Structure Comportement

Design pattern

◮ Solution generale a un probleme courant en conceptionlogicielle

◮ Definition des interactions entre classes ou objets

◮ Independant du langage de programmation et du paradigme

◮ Different des bibliotheques

◮ Possibilite de combiner des patterns

◮ Amelioration de l’efficacite, la robustesse, le temps dedeveloppement, la lisibilite du code

2 / 18

Introduction Creation Structure Comportement

Design pattern

◮ Nom du pattern, description du probleme, description de lasolution

◮ Categories :

◮ Creation : instanciation et configuration des objets◮ Structure : organisation des classes◮ Comportement : interactions entre les objets

2 / 18

Introduction Creation Structure Comportement

Factory Method

Contexte

◮ Creation d’un objet, mais difficile de connaitre precisement dequelle classe

Exemples

◮ Differents types de documents

◮ Differentes methodes pour un meme type de resultats (rendugraphique, classification supervisee)

3 / 18

Introduction Creation Structure Comportement

Factory Method

Solution naıve

◮ Creation directe de l’objet

Problemes

◮ Necessite de connaitre les constructeurs, les parametres, etc.

3 / 18

Introduction Creation Structure Comportement

Factory Method

Pattern

◮ Association de classes de creation

◮ Methode de creation dans les classes de creation concretes

◮ Hierarchie identique aux classes a creer

◮ Les createurs peuvent contenir des constructeurs et desmethodes de configuration des objets crees

3 / 18

Introduction Creation Structure Comportement

Factory Method

Schema

3 / 18

Introduction Creation Structure Comportement

Factory Method

Exemple

public abstract class ClusteringMethod {

...

Clustering getClustering(Data data);

...

}

3 / 18

Introduction Creation Structure Comportement

Factory Method

Exemple

public class Kmeans extends ClusteringMethod {

public Kmeans(int k) {

...

}

...

public Clustering getClustering(Data data) {

...

return clustering;

}

}

3 / 18

Introduction Creation Structure Comportement

Factory Method

Exemple

public abstract class ClusteringMethodCreator {

public ClusteringMethod createClusteringMethod();

}

3 / 18

Introduction Creation Structure Comportement

Factory Method

Exemple

public class KmeansCreator extends ClusteringMethodCreator

{

private int k = 2 ;

public ClusteringMethod createClusteringMethod() {

return new Kmeans(this.k);

}

public void setK(int k) {

this.k = k ;

}

}

3 / 18

Introduction Creation Structure Comportement

Abstract Factory

Contexte

◮ Ensemble de classes liees entre elles

◮ Plusieurs versions de ces classes

Exemples

◮ Look-and-feels de widgets d’une IHM

◮ Portabilite de code (version Linux, Mac, Windows)

4 / 18

Introduction Creation Structure Comportement

Abstract Factory

Solution naıve

◮ Creation des objets de facon individuelle

Problemes

◮ Il est necessaire de faire attention a la comptatibilite desobjets a chaque creation

4 / 18

Introduction Creation Structure Comportement

Abstract Factory

Pattern

◮ Interface AbstractFactory contenant des methodes de creationpour chaque element

◮ Realisations de l’interface pour chaque famille d’elements

4 / 18

Introduction Creation Structure Comportement

Abstract Factory

Schema

4 / 18

Introduction Creation Structure Comportement

Abstract Factory

Exemple

public interface Window {

...

public void display () ;

...

}

public interface Button {

...

}

4 / 18

Introduction Creation Structure Comportement

Abstract Factory

Exemple

public class SwingWindow extends JFrame implements Window

{

...

public void display () {

this.setVisible(true);

}

...

}

public class SwingButton extends JButton implements Button

{

...

}

4 / 18

Introduction Creation Structure Comportement

Abstract Factory

Exemple

public interface WidgetFactory {

public Window createWindow () ;

public Window createButton () ;

...

}

4 / 18

Introduction Creation Structure Comportement

Abstract Factory

Exemple

public class SwingWidgetFactory implements WidgetFactory {

public Window createWindow () {

return new SwingWindow();

}

public Button createButton () {

return new SwingButton();

}

...

}

4 / 18

Introduction Creation Structure Comportement

Singleton

Contexte

◮ Classe instanciee une seule fois dans le programme

◮ Acces a l’instance a des endroits tres varies

Exemples

◮ Fenetre principale d’une IHM

◮ Acces a un fichier de configuration

◮ Acces a une base de donnee

5 / 18

Introduction Creation Structure Comportement

Singleton

Solution naıve

◮ Creation d’une instance

◮ Passage en parametre vers toutes les zones du code qui ontbesoin de l’utiliser

Problemes

◮ Difficile a maintenir

5 / 18

Introduction Creation Structure Comportement

Singleton

Pattern

◮ Constructeur prive

◮ Instance en tant qu’attribut statique de la classe

◮ Methode statique d’acces a l’instance

5 / 18

Introduction Creation Structure Comportement

Singleton

Schema

5 / 18

Introduction Creation Structure Comportement

Singleton

Exemple

public class MainFrame extends JFrame {

private static MainFrame instance;

private MainFrame() {

...

}

public static getInstance () {

if (MainFrame.instance == null)

MainFrame.instance = new MainFrame();

return MainFrame.instance;

}

}

5 / 18

Introduction Creation Structure Comportement

Adapter

Contexte

◮ Reutilisation de code ancien

◮ Code efficace mais complexe

◮ Interface inadaptee

6 / 18

Introduction Creation Structure Comportement

Adapter

Solution naıve

◮ Reecrire le programme avec une nouvelle interface

Problemes

◮ Il faut reecrire le programme. . .

6 / 18

Introduction Creation Structure Comportement

Adapter

Pattern

◮ Un Adapter etend ou contient l’ancienne classe et realise lanouvelle interface

6 / 18

Introduction Creation Structure Comportement

Adapter

Schema

6 / 18

Introduction Creation Structure Comportement

Adapter

Exemple

public class TextDrawer {

...

public void drawText(String text) { ...

}

}

6 / 18

Introduction Creation Structure Comportement

Adapter

Exemple

public interface Shape {

...

public void draw();

...

}

public class Line implements Shape {

...

public void draw() {

...

}

...

}

6 / 18

Introduction Creation Structure Comportement

Adapter

Exemple

public class TextShape extends TextDrawer implements Shape

{

private String text;

public TextShape(String text) {

this.text = text ;

}

...

public void draw() {

this.drawText(this.text);

}

...

}

6 / 18

Introduction Creation Structure Comportement

Decorator

Contexte

◮ Ajout dynamique de fonctionnalite a un objet

Exemples

◮ Ajout de decoration dans un widget

◮ Filtrage

◮ Verification d’autorisation (demande de mot de passe)

7 / 18

Introduction Creation Structure Comportement

Decorator

Solution naıve

◮ Integrer toutes les fonctionnalites dans la classe

◮ Utiliser des conditionnelles pour utiliser une fonctionnalite oupas

Problemes

◮ Augmentation de la complexite du programme

7 / 18

Introduction Creation Structure Comportement

Decorator

Pattern

◮ Une interface et une classe qui la realise avec lecomportement de base

◮ Des classes Decorator qui sont composees d’une instance del’interface et qui rajoute une fonctionnalite

7 / 18

Introduction Creation Structure Comportement

Decorator

Schema

7 / 18

Introduction Creation Structure Comportement

Decorator

Exemple

public abstract class Stream {

private Buffer buffer;

...

public void put(Data data) {

...

if (this.buffer.isFull())

this.flushBuffer(this.buffer);

}

public abstract void flushBuffer(Buffer buffer);

...

}

7 / 18

Introduction Creation Structure Comportement

Decorator

Exemple

public class FileStream extends Stream {

private File file;

...

public void append(Buffer buffer, File file) {

...

}

public void flushBuffer(Buffer buffer) {

this.append(buffer, this.file);

}

...

}

7 / 18

Introduction Creation Structure Comportement

Decorator

Exemple

public class CompressingStream extends Stream {

private Stream stream;

...

public Buffer compress(Buffer buffer) {

...

return compressedBuffer;

}

public void flushBuffer(Buffer buffer) {

Buffer compressedBuffer = this.compredd(buffer);

this.stream.flushBuffer(compressedBuffer);

}

...

}

7 / 18

Introduction Creation Structure Comportement

Proxy

Contexte

◮ Objets couteux a l’instanciation (temps de calcul, espacememoire)

◮ Les objets doivent exister mais ne sont pas necessairementmanipules (du moins pas en meme temps)

Exemples

◮ Images ou videos d’un document

◮ Connexion a des bases de donnees

8 / 18

Introduction Creation Structure Comportement

Proxy

Solution naıve

◮ Creer les objets entierement a l’instanciation

Problemes

◮ Processus lent au demarrage et gourmand en memoire

8 / 18

Introduction Creation Structure Comportement

Proxy

Pattern

◮ Classe Proxy avec meme interface que l’objet a charger

◮ Manipulation du Proxy et instanciation de l’objet a lademande

8 / 18

Introduction Creation Structure Comportement

Proxy

Schema

8 / 18

Introduction Creation Structure Comportement

Proxy

Exemple

public interface Image {

public void display (DrawingZone dz) ;

}

8 / 18

Introduction Creation Structure Comportement

Proxy

Exemple

public class RealImage implements Image {

public RealImage (File file) {

...

}

public void display (DrawingZone dz) {

...

}

}

8 / 18

Introduction Creation Structure Comportement

Proxy

Exemple

public class ProxyImage implements Image {

private File imageFile;

private RealImage realImage;

public ProxyImage (File file) {

this.imageFile = file;

}

public void display (DrawingZone dz) {

this.realImage = new RealImage(this.imageFile);

this.realImage.display(dz);

//this.realImage = null;

}

}

8 / 18

Introduction Creation Structure Comportement

Facade

Contexte

◮ Systeme complexe

◮ Classes tres nombreuses

◮ Nombre de fonctionnalites relativement faible

9 / 18

Introduction Creation Structure Comportement

Facade

Solution naıve

◮ Utiliser les classes telles qu’elles existent

Problemes

◮ Systeme difficile a utiliser

◮ Necessite de connaitre toutes les classes

9 / 18

Introduction Creation Structure Comportement

Facade

Pattern

◮ Une classe Facade sert de point d’entree au systeme

◮ Toutes les interactions au systeme se font au travers de laFacade

9 / 18

Introduction Creation Structure Comportement

Facade

Schema

9 / 18

Introduction Creation Structure Comportement

Facade

Exemple

public class Tokenizer {

public Token[] tokenize(File file) {

...

}

}

9 / 18

Introduction Creation Structure Comportement

Facade

Exemple

public class Parser {

public ProgramNode parse(Token[] tokens) {

...

}

}

9 / 18

Introduction Creation Structure Comportement

Facade

Exemple

public abstract class ProgramNode {

private ProgramNode[] children;

public void addNode(ProgramNode node) {

...

}

}

9 / 18

Introduction Creation Structure Comportement

Facade

Exemple

public class InstructionNode extends ProgramNode {

private Instruction instruction;

...

public Instruction getInstruction() {

return this.instruction;

}

}

public class VariableNode extends ProgramNode {

private int label;

...

public int getLabel() {

return this.label;

}

}

9 / 18

Introduction Creation Structure Comportement

Facade

Exemple

public class AssemblerGenerator {

public Code generate(ProgramNode root) {

...

}

}

9 / 18

Introduction Creation Structure Comportement

Facade

Exemple

public class BinaryGenerator {

public void generate(Code assembler, File file) {

...

}

}

9 / 18

Introduction Creation Structure Comportement

Facade

Exemple

public class Compiler {

public void generate(File input, File output) {

Tokenizer tokenizer = new Tokenizer();

Token[] tokens = tokenizer.tokenize(input);

Parser parser = new Parser();

ProgramNode root = parser.parse(tokens);

AssemblerGenerator ag = new AssemblerGenerator();

Code assembler = ag.generate(root);

BinaryGenerator bg = new BinaryGenerator();

bg.generate(assembler, output);

}

}

9 / 18

Introduction Creation Structure Comportement

Command

Contexte

◮ Objets avec action a effectuer

◮ Une meme action peut etre effecutee par plusieurs objets

Exemples

◮ Bouttons, items, etc. d’une IHM

10 / 18

Introduction Creation Structure Comportement

Command

Solution naıve

◮ Implantation des actions dans les objets

Problemes

◮ Repetition de code

◮ Difficulte de maintenance

10 / 18

Introduction Creation Structure Comportement

Command

Pattern

◮ Une interface Command qui contient une methode execute

◮ Une realisation de l’interface pour chaque commande

◮ Integration d’une commande dans l’object

10 / 18

Introduction Creation Structure Comportement

Command

Schema

10 / 18

Introduction Creation Structure Comportement

Command

Exemple

public interface Command {

public void execute();

}

public class CmdOpen implements Command{

public void execute() {

File file = new FileChooser().getSelectedFile();

Document document = DocumentCreator.create(file);

ApplicationGui gui = ApplicationGui.getInstance();

gui.addDocument(document);

}

10 / 18

Introduction Creation Structure Comportement

Command

Exemple

public class CmdButton extends Button {

private Command command;

public CmdButton(String label, Command command) {

super(label);

this.command = command;

}

public void pressed () {

this.command.execute();

}

}

10 / 18

Introduction Creation Structure Comportement

Command

Exemple

public class ApplicationGui {

private ApplicationGui instance = new ApplicationGui();

private ApplicationGui() {

...

Button open = new CmdButton("Open", new CmdOpen());

this.addButton(open);

...

}

public static ApplicationGui getInstance () {

return ApplicationGui.instance;

}

private void addButton(Button button) {

...

}

}

10 / 18

Introduction Creation Structure Comportement

Iterator

Contexte

◮ Liste d’objets

◮ Plusieurs parcours simultanes

11 / 18

Introduction Creation Structure Comportement

Iterator

Solution naıve

◮ Parcours avec les methodes d’acces a la liste

Problemes

◮ Necessite de connaitre la structure de la liste (liste chaınee,tableau, arbre, etc.)

11 / 18

Introduction Creation Structure Comportement

Iterator

Pattern

◮ Utiliser une classe Iterator qui possede des methodes deparcours standardisees

◮ Un Iterator par type de liste

11 / 18

Introduction Creation Structure Comportement

Iterator

Schema

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple

public interface List {

public Iterator getIterator();

}

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple

public class LinkedList {

private Element currentElement;

private LinkedList nextElement;

public LinkedList (Element element) {

this.currentElement = element;

this.nextElement = null;

}

public Element getCurrentElement() {

return this.currentElement;

}

public LinkedList getNextElement() {

return this.nextElement;

}

...

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple...

public boolean isLastElement() {

return this.nextElement == null;

}

public Iterator getIterator() {

return new LinkedListIterator(this);

}

public void add(Element element) {

if (this.nextElement == null)

this.nextElement = new LinkedList(element)

else

this.nextElement.add(element);

}

}

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple

public class ArrayList {

private Element[] elements;

public ArrayList(Element[] elements) {

this.elements = elements;

}

public Element getElement(int index) {

return this.elements[index];

}

public int getElementCount() {

return this.elements.length;

}

public Iterator getIterator() {

return new ArrayListIterator(this);

}

}

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple

public abstract class Iterator {

protected List list;

public Iterator (List list) {

this.list = list ;

this.initialize();

}

public abstract void initialize();

public abstract Element getCurrentElement();

public abstract void next();

public abstract boolean isDone();

}

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple

public class LinkedListIterator {

private LinkedList current;

public LinkedListIterator (LinkedList list) {

super(list);

}

public void initialize() {

this.current = (LinkedList)this.list;

}

public Element getCurrentElement() {

return this.current.getCurrentElement();

}

...

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple...

public void next() {

this.current = this.current.getNextElement();

}

public boolean isDone() {

return this.current == null;

}

}

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple

public class ArrayListIterator {

private int current;

public ArrayListIterator (ArrayList list) {

super(list);

}

public void initialize() {

this.currentIndex = 0 ;

}

public Element getCurrentElement() {

ArrayList array = (ArrayList)this.list;

return array.getElement(this.current);

}

...

11 / 18

Introduction Creation Structure Comportement

Iterator

Exemple...

public void next() {

this.current++;

}

public boolean isDone() {

ArrayList array = (ArrayList)this.list;

return this.current == array.getElementCount();

}

}

11 / 18

Introduction Creation Structure Comportement

Observer

Contexte

◮ Un objet qui varie

◮ Dependance vers d’autres composants

Exemples

◮ Plusieurs vues sur un objet edite par l’utilisateur

◮ Algorithme iteratif, traitement des resultats intermediaires(algorithme d’optimisation, affichage de la meilleure solutioncourante, de la meilleure evaluation etc.)

12 / 18

Introduction Creation Structure Comportement

Observer

Solution naıve

◮ Integrer les elements dependant en dur dans la classemodifiable

Problemes

◮ Peu modulaire

◮ Dependance forte entre la classe et le reste de l’application

12 / 18

Introduction Creation Structure Comportement

Observer

Pattern

◮ La classe possede un certain nombre d’instance de la classeObserver

◮ La classe previent chaque Observer qu’elle a ete modifiee

◮ Les instance d’Observer utilisent des methodes d’acces a laclasse pour se mettre a jour

◮ Les instance d’Observer peuvent eventuellement activer laclasse observee

12 / 18

Introduction Creation Structure Comportement

Observer

Schema

12 / 18

Introduction Creation Structure Comportement

Observer

Exemple

public class GeneticAlgorithm {

private ArrayList<Observer> observers;

private int generations;

...

public void attach(Observer observer) {

this.observers.add(observer);

observer.setSubject(this);

}

public double getBestFitness() {

...

}

public Solution getBestSolution() {

...

}

...

12 / 18

Introduction Creation Structure Comportement

Observer

Exemple...

private void notify() {

for(Observer observer : this.observers)

observer.update();

}

private void createPopulation() {

...

}

private void evaluation() {

...

}

private void reproduction() {

...

}

...

12 / 18

Introduction Creation Structure Comportement

Observer

Exemple...

public void run() {

this.createPopulation();

this.evaluation();

this.notify();

for(int g = 0 ; g < this.generations; g++) {

this.reproduction();

this.evaluation();

this.notify();

}

}

}

12 / 18

Introduction Creation Structure Comportement

Observer

Exemple

public abstract class Observer {

GeneticAlgorithm subject;

public void setSubject(GeneticAlgorithm subject) {

this.subject = subject;

}

public abstract void update();

}

}

12 / 18

Introduction Creation Structure Comportement

Observer

Exemple

public class ChartObserver implements Observer {

ArrayList<Double> fitness;

private Chart chart;

public ChartObserver(Chart chart) {

this.fitness = new ArrayList<Double>();

this.chart = chart;

}

public void update() {

double fitness = this.subject.getBestFitness();

this.fitness.add(fitness);

this.char.plot(this.fitness);

}

}

12 / 18

Introduction Creation Structure Comportement

State

Contexte

◮ Etat d’une classe variable avec le temps

◮ Comportement de la classe variable dependant de son etat

Exemples

◮ Connexion reseau (fermee, etablie)

◮ Logiciel de dessin (effet de la souris sur la zone de dessin)

13 / 18

Introduction Creation Structure Comportement

State

Solution naıve

◮ Variable (entier ou enumeration) codant l’etat

◮ Conditionnelle (if/else ou switch) sur les comportementsdependant de l’etat

Problemes

◮ Complexite de la classe (methodes tres longues)

◮ Difficile de rajouter un etat (necessite de verifier chaqueconditionnelle)

13 / 18

Introduction Creation Structure Comportement

State

Pattern

◮ Utiliser une classe qui represente l’etat et le comportementassocie

13 / 18

Introduction Creation Structure Comportement

State

Schema

13 / 18

Introduction Creation Structure Comportement

State

Exemple

public class DrawingController {

private Tool selectedTool;

public DrawingController() {

this.selectedTool = new Brush();

}

public void mousePressed() {

this.selectedTool.mousePressed();

}

public void setTool(Tool tool) {

this.selectedTool = tool ;

}

}

13 / 18

Introduction Creation Structure Comportement

State

Exemple

public interface Tool {

public void mousePressed();

}

13 / 18

Introduction Creation Structure Comportement

State

Exemple

public class Brush implements Tool {

public void mousePressed() {

MainFrame mainFrame = MainFrame.getInstance();

DrawingZone zone = mainFrame.getCurrentDrawingZone();

Mouse mouse = Mouse.getInstance();

Coordinates xy = zone.getImageCoordinates (mouse);

Color color = mainFrame.getCurrentColor();

zone.drawPixel(xy, color);

}

}

13 / 18

Introduction Creation Structure Comportement

State

Exemple

public class Paint implements Tool {

public void mousePressed() {

MainFrame mainFrame = MainFrame.getInstance();

DrawingZone zone = mainFrame.getCurrentDrawingZone();

Mouse mouse = Mouse.getInstance();

Coordinates xy = zone.getImageCoordinates (mouse);

Color oldColor = zone.getColor(xy);

Color newColor = mainFrame.getCurrentColor();

zone.seedFill(xy, oldColor, newColor);

}

}

13 / 18

Introduction Creation Structure Comportement

Strategy

Contexte

◮ Plusieurs algorithmes

◮ Fonctionnements differents

◮ Resultats du meme type

Exemples

◮ Algorithmes de rendu graphique

◮ Algorithmes d’apprentissage

◮ Algorithmes de compression

14 / 18

Introduction Creation Structure Comportement

Strategy

Solution naıve

◮ Utiliser l’heritage

Problemes

◮ Difficile de changer de strategie dynamiquement

◮ Pas de separation entre le contexte et l’algorithme

14 / 18

Introduction Creation Structure Comportement

Strategy

Pattern

◮ Utiliser une classe qui represente la strategie et lecomportement associe

14 / 18

Introduction Creation Structure Comportement

Strategy

Schema

14 / 18

Introduction Creation Structure Comportement

Strategy

Exemple

public class Scene {

private ArrayList<Object3D> objects;

private Display strategy;

...

public void addObject(Object3D object) {

this.objects.add(object);

}

public void setStrategy(Display strategy) {

this.strategy = strategy;

}

public void display() {

this.strategy.display(this.objects);

}

}

14 / 18

Introduction Creation Structure Comportement

Strategy

Exemple

public interface Display {

public void display(ArrayList<Object3D> objects);

}

public class RayTracer implements Display {

public void display(ArrayList<Object3D> objects) {

...

}

}

public class BeamTracer implements Display {

public void display(ArrayList<Object3D> objects) {

...

}

}

14 / 18

Introduction Creation Structure Comportement

Combined Method

Contexte

◮ Ensemble de methodes utilisees souvent ensemble (l’une apresl’autre), mais parfois independamment

15 / 18

Introduction Creation Structure Comportement

Combined Method

Solution naıve

◮ Utiliser les methodes les unes apres les autres

Problemes

◮ Risque d’oublier d’une des methodes, d’inverser l’ordre, etc.

15 / 18

Introduction Creation Structure Comportement

Combined Method

Pattern

◮ Rajouter une methode qui combine les methodes dependantestout en conservant publiques chacune d’entre elle

15 / 18

Introduction Creation Structure Comportement

Combined Method

Schema

15 / 18

Introduction Creation Structure Comportement

Combined Method

Exemple

public class Morphology {

...

public Image erosion(Image i, Struct e) {

...

}

public Image dilatation(Image i, Struct e) {

...

}

public Image complement(Image i) {

...

}

public Image intersection(Image i1, Image i2) {

...

}

...

15 / 18

Introduction Creation Structure Comportement

Combined Method

Exemple...

public void opening(Image i, Struct e) {

Image t = this.erosion(i, e) ;

return this.dilatation(t, e) ;

}

public void closing(Image i, Struct e) {

Image t = this.dilatation(i, e) ;

return this.erosion(t, e) ;

}

public void hitOrMiss(Image i, Struct e1, Struct e2) {

Image t1 = this.erosion(i, e1) ;

Image c = this.complement(i);

Image t2 = this.erosion(c, e2) ;

return this.intersection(t1, t2) ;

}

}15 / 18

Introduction Creation Structure Comportement

Template Method

Contexte

◮ Algorithme compose de plusieurs etapes

◮ Plusieurs versions de l’algorithme

Exemples

◮ Ouverture d’un document

◮ Algorithme d’apprentissage

◮ Etc.

16 / 18

Introduction Creation Structure Comportement

Template Method

Solution naıve

◮ Ecrire en entier chaque version de l’algorithme dans chacunedes sous-classes

Problemes

◮ Duplication de code

◮ Maintenance difficile

16 / 18

Introduction Creation Structure Comportement

Template Method

Pattern

◮ Squelette de l’algorithme dans une classe abstraite

◮ Implantation de chacune des etapes dans les sous-classes

16 / 18

Introduction Creation Structure Comportement

Template Method

Schema

16 / 18

Introduction Creation Structure Comportement

Template Method

Exemple

public abstract class KmeansBasedAlgorithm {

...

public void learn() {

this.initializeSeeds();

for(int i = 0 ; i < iterations; i++) {

this.modifyMembership();

this.modifySeeds();

}

}

protected abstract void initializeSeeds();

protected abstract void modifyMembership();

protected abstract void modifySeeds();

}

16 / 18

Introduction Creation Structure Comportement

Template Method

Exemple

public class FuzzyCmeans extends KmeansBasedAlgorithm {

...

protected void initializeSeeds() {

...

}

protected void modifyMembership() {

...

}

protected void modifySeeds() {

...

}

}

16 / 18

Introduction Creation Structure Comportement

Resource Pool

Contexte

◮ Ensemble limite de ressources

◮ Acces a ces ressources frequent a divers endroits duprogramme

Exemples

◮ Threads

◮ Connexion reseau

17 / 18

Introduction Creation Structure Comportement

Resource Pool

Solution naıve

◮ Creer, preparer et detruire les ressources a la volee

Problemes

◮ Ralentissement a chaque acces a une ressource

17 / 18

Introduction Creation Structure Comportement

Resource Pool

Pattern

◮ Conserver un ensemble de ressources accessibles auprogramme

◮ Chaque acces retire une ressource de l’ensemble

◮ Apres utilisation, la ressource est replacee dans l’ensemble

17 / 18

Introduction Creation Structure Comportement

Resource Pool

Schema

17 / 18

Introduction Creation Structure Comportement

Resource Pool

Exemple

public class PeerPool {

private PeerPool instance;

private ArrayList<Peer> peers;

private PeerPool() {

this.peers = new ArrayList<Peer> () ;

}

public PeerPool static getInstance() {

return PeerPool.instance;

}

...

17 / 18

Introduction Creation Structure Comportement

Resource Pool

Exemple...

public Peer getPeer() {

Peer peer = null ;

if (this.peers.size() > 0) {

peer = this.peers.get(0);

this.peers.remove(0);

}

return peer;

}

public void insertPeer (Peer peer) {

this.peers.add(peer);

}

}

17 / 18

Introduction Creation Structure Comportement

Resource Pool

Exemple

public interface Peer {

public void handleTask(Task task);

}

public class Client {

...

private Task getTask() {

...

}

public void remoteAction() {

PeerPool pool = PeerPool.getInstance();

Peer peer = pool.getPeer();

peer.handleTask(this.getTask());

pool.insert(peer);

}

17 / 18

Introduction Creation Structure Comportement

Questions

18 / 18