Patrons de conception

Les patrons de conception (design patterns) apportent des solutions algorithmiques et d'implémentation aux problèmes courants rencontrés dans le cadre de la conception orientée objet.

Le Singleton (Singleton)

Problématique : Créer et avoir toujours à disposition une unique instance d'une classe

Le pattern Singleton apporte une solution aux cas où une unique instance d'une classe doit exister dans un programme (pour une gestion d'un pool de connexions, une gestion du cache, une instance d'application…)

Diagramme de classes

Implémentation en java

public final class Singleton {

  private static Singleton instance;

  private Singleton() {
    // constructeur
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class) {
        instance = new Singleton();
      }
    }
    return instance;
  }

  @Override
  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }
}

Utilisation

Il est ensuite possible de faire appel à la méthode getInstance qui retournera toujours l'instance unique de singleton.

Singleton.getInstance();

La Fabrique (Factory)

Problématique : Créer différents objets dont le type peut varier à l'exécution, en fonction du déroulement du programme

Objectifs

La fabrique est une classe de création d'objets, de différents types, héritant d'une classe de base, ou implémentant une interface. Elle permet la création d'objets dynamiquement en fonction de paramètres passés.

Caractéristiques

  • La fabrique étant souvent unique dans le programme, elle peut utiliser le pattern Singleton
  • Les paramètres passés à la fabrique déterminent le type d'instance à créer

Diagramme de classes

Implémentation en java

Les différents types à créer (héritant d'un type générique)

public abstract class Animal{
   public abstract void myName();
}

public class Chat extends Animal{
   public void myName(){
     System.out.println("Je suis un Chat");
   }
}

public class Chien extends Animal{
   public void myName(){
     System.out.println("Je suis un Chien");
   }
}

La fabrique :

public class FabriqueAnimal{

    private static FabriqueAnimal instance = new FabriqueAnimal();
    
    private FabriqueAnimal(){}

    public static FabriqueAnimal getFabriqueAnimalInstance(){
        return instance ;
    }

    public Animal getAnimal(String typeAnimal) throws ExceptionCreation{
        Animal result=null;
        switch(typeAnimal){
            case "chat":
                result= new Chat();
                break;
            case "chien":
                result=new Chien();
                break;
            default:
                throw new ExceptionCreation("Impossible de créer un " + typeAnimal);
                break;
        }
        return result;
    }
}

Utilisation :

public class DemoFabrique{
   public static void main(String [] args){
     FabriqueAnimal fabrique =  FabriqueAnimal.getFabriqueAnimalInstance();
     Animal animal = FabriqueAnimal.getAnimal("chat");
     animal.myName(); 
   }
}

La Fabrique abstraite (Abstract Factory)

Problématique : Créer différents objets dont le type peut varier à l'exécution, en fonction du déroulement du programme, dissocier création et utilisation pour permettre l'ajout de nouveaux objets, sans modifier le code du programme utilisateur.

Objectifs

La fabrique est un créateur d'objets, de différents types, héritant d'une classe de base, ou implémentant une interface. Elle permet d'isoler la création des objets de leur utilisation.
On peut ainsi ajouter de nouveaux objets dérivés sans modifier le code qui utilise l'objet de base.

Implémentation en java

Les différents types d'objet à créer et leur classe de base :

public abstract class Button{
    private String caption;
    public abstract void paint();
     
    public String getCaption(){
        return caption;
    }

    public void setCaption(String caption){
        this.caption = caption;
    }
}
 
class WinButton extends Button{
    public void paint(){
        System.out.println("I'm a WinButton: "+ getCaption());
    }
}

class OSXButton extends Button{
    public void paint(){
        System.out.println("I'm a OSXButton: "+ getCaption());
    }
}

Les factories concrètes et leur classe abstraite :

/*
 * GUIFactory example
 */
public abstract class GUIFactory{
    public static GUIFactory getFactory(){
        int sys = readFromConfigFile("OS_TYPE");
        if (sys == 0)
            return(new WinFactory());
        else
            return(new OSXFactory());
    }
    public abstract Button createButton();
}

class WinFactory extends GUIFactory{
    public Button createButton(){
        return(new WinButton());
    }
}

class OSXFactory extends GUIFactory{
    public Button createButton(){
        return(new OSXButton());
    }
}

Utilisation :

public class DemoAbstractFactory{
    public static void main(String[] args){
        GUIFactory aFactory = GUIFactory.getFactory();
        Button aButton = aFactory.createButton();
        aButton.setCaption("Jouer");
        aButton.paint();
    }
}

Limites

  • Introduit une certaine complexité dans le développement, parfois à éviter

Le poids mouche (Flyweight)

Problématique : Eviter de créer un trop grand nombre d'instances d'une classe ayant des propriétés intrinsèques

Le poids mouche permet de factoriser le nombre d'instances à créer d'une classe, en permettant la réutilisation d'instance existantes.

Diagramme de classes

Implémentation en java

Source : http://www.journaldev.com/1562/flyweight-pattern-in-java-example-tutorial

Création de formes (Shape), de types concrets (Line, oval…)

Models

package models;

import java.awt.Color;
import java.awt.Graphics;

public interface Shape {
	public void draw(Graphics g, int x, int y, int width, int height, Color color);
}

package models;

import java.awt.Color;
import java.awt.Graphics;

public class Line implements Shape {
	@Override
	public void draw(Graphics g, int x, int y, int width, int height, Color color) {
		g.setColor(color);
		g.drawLine(x, y, width, height);
	}
}

package models;

import java.awt.Color;
import java.awt.Graphics;

public class Oval implements Shape {

	private boolean fill;

	public Oval(boolean fill) {
		this.fill = fill;
	}

	@Override
	public void draw(Graphics g, int x, int y, int width, int height, Color color) {
		g.setColor(color);
		g.drawOval(x, y, width, height);
		if (fill) {
			g.fillOval(x, y, width, height);
		}
	}
}

Factory

package models;

import java.util.HashMap;

public class ShapeFactory {

	private static final HashMap<ShapeType, Shape> shapes = new HashMap<ShapeType, Shape>();

	public static Shape getShape(ShapeType type) {
		Shape shapeImpl = shapes.get(type);

		if (shapeImpl == null) {
			switch (type) {
			case OVAL_FILL:
				shapeImpl = new Oval(true);
				break;
			case OVAL:
				shapeImpl = new Oval(false);
				break;
			case LINE:
				shapeImpl = new Line();
				break;
			}
			shapes.put(type, shapeImpl);
		}
		return shapeImpl;
	}

	public static enum ShapeType {
		OVAL_FILL, OVAL, LINE;
	}
}

Utilisation

public class DemoFlyweight extends JFrame {

	private static final long serialVersionUID = -1350200437285282550L;
	private final int WIDTH;
	private final int HEIGHT;

	private static final ShapeType shapes[] = { ShapeType.LINE, ShapeType.OVAL_FILL, ShapeType.OVAL };
	private static final Color colors[] = { Color.RED, Color.GREEN, Color.YELLOW };

	public DemoFlyweight(int width, int height) {
		this.WIDTH = width;
		this.HEIGHT = height;
		Container contentPane = getContentPane();

		JButton startButton = new JButton("Draw");
		final JPanel panel = new JPanel();

		contentPane.add(panel, BorderLayout.CENTER);
		contentPane.add(startButton, BorderLayout.SOUTH);
		setSize(WIDTH, HEIGHT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);

		startButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				Graphics g = panel.getGraphics();
				for (int i = 0; i < 40; ++i) {
					Shape shape = ShapeFactory.getShape(getRandomShape());
					shape.draw(g, getRandomX(), getRandomY(), getRandomWidth(), getRandomHeight(), getRandomColor());
				}
			}
		});
	}

	private ShapeType getRandomShape() {
		return shapes[(int) (Math.random() * shapes.length)];
	}

	private int getRandomX() {
		return (int) (Math.random() * WIDTH);
	}

	private int getRandomY() {
		return (int) (Math.random() * HEIGHT);
	}

	private int getRandomWidth() {
		return (int) (Math.random() * (WIDTH / 10));
	}

	private int getRandomHeight() {
		return (int) (Math.random() * (HEIGHT / 10));
	}

	private Color getRandomColor() {
		return colors[(int) (Math.random() * colors.length)];
	}

	public static void main(String[] args) {
		new DemoFlyweight(500, 600);
	}
}

MVC 2

MVC2 est un patron de conception dont la volonté est de séparer les données, les traitements et la présentation. MVC2 permet de segmenter une application en trois composants essentiels :

  • Le modèle
  • Le contrôleur
  • Les vues

MVC2 est une variante de MVC, dans laquelle le contrôleur est unique (contrairement à MVC où le rôle du contrôleur est assuré par plusieurs éléments).

Nombre de frameworks permettent une implémentation de MVC ou MVC2 facilitée.

Le Modèle

Le modèle correspond aux classes et objets métiers. Le modèle est responsable de la gestion de ces données, et en assure l'intégrité. Il ne doit faire aucune référence aux vues, pas plus qu'au contrôleur.

Le contrôleur

Le contrôleur synchronise (via évènements) les vues et le modèle. Il est responsable de la logique applicative. Le contrôleur n'effectue aucun traitement, mais se contente de solliciter le modèle adéquat, ou d'afficher la vue correspondante.

Les vues

Les vues correspondent à l'IHM, elles affichent les résultats fournis par le modèle, en réponse aux actions de l'utilisateur.

Voir MVC expliqué à mam

Injection de dépendance (dependency injection)

Problématique : Eviter une dépendance directe entre deux classes, en définissant dynamiquement la dépendance plutôt que statiquement.

Une classe A dépend d'une autre classe B quand la classe A possède un attribut de type B, ou possède une méthode utilisant la classe B (type de paramètre, valeur de retour, variable locale, appel de méthode de la classe B).

Pour mettre en œuvre l'injection de dépendance :

Créer une interface I déclarant les méthodes de la classe B utilisées par la classe A ;

public interface I{
    public void doSomething();
}

Déclarer la classe B comme implémentation de cette interface I ;

public class B implements I{
    public void doSomething(){
        system.out.println("something done !");
}

Remplacer toute référence à la classe B par des références à l'interface I ; Si la classe A instancie des instances de B à son initialisation, alors remplacer l'instanciation par un passage d'une instance de l'interface I au(x) constructeur(s) de A ; Si besoin, ajouter une méthode pour spécifier l'instance de l'interface I à utiliser.

public class A{
    private I injected;
    
    public A(I injected){
        this.injected=injected;
    }
}

Observer/observable

Delayed Queue

Permet de gérer une liste d'éléments en sortie FIFO avec délai.

Références

Discussion

Glass Glue, 2020/10/31 16:02

Glass Glue https://www.supplygoo.com/glass-glue/

xqxxcznnte, 2020/10/31 05:39

slam4:poo:designpattern [SlamWiki] <a href=“http://www.g3p9wfuz1z0617t658w062u0ta9rssv5s.org/”>axqxxcznnte</a> xqxxcznnte http://www.g3p9wfuz1z0617t658w062u0ta9rssv5s.org/ [url=http://www.g3p9wfuz1z0617t658w062u0ta9rssv5s.org/]uxqxxcznnte[/url]

longchamp handbags, 2020/10/30 04:25

I want to show appreciation to you for bailing me out of this type of situation. Just after looking through the search engines and coming across basics that were not beneficial, I assumed my entire life was gone. Existing without the presence of solutions to the problems you have sorted out all through the short post is a critical case, as well as the kind that might have negatively affected my entire career if I had not encountered your web blog. Your actual skills and kindness in controlling almost everything was invaluable. I am not sure what I would've done if I had not come across such a thing like this. I can at this moment relish my future. Thanks so much for the impressive and sensible help. I will not be reluctant to suggest the website to anyone who wants and needs recommendations about this issue. longchamp handbags http://www.longchampshandbags.us.org

yeezy, 2020/10/30 04:25

I precisely wanted to thank you so much again. I am not sure the things that I would have used without the secrets documented by you about that area. It was actually a very fearsome crisis for me personally, nevertheless considering this specialized style you solved the issue forced me to leap for gladness. Extremely happier for this service and even hope that you realize what a great job you have been doing teaching some other people all through a web site. I'm certain you've never got to know any of us. yeezy http://www.yeezyshoessupply.com

kd shoes, 2020/10/30 04:25

A lot of thanks for each of your work on this website. My mum really loves making time for internet research and it's easy to understand why. We all notice all relating to the dynamic ways you deliver priceless tips on your blog and as well welcome contribution from other individuals on that area while our simple princess is without question becoming educated a lot. Take pleasure in the rest of the year. You're conducting a wonderful job. kd shoes http://www.kd-shoes.us

supreme outlet, 2020/10/30 04:25

I am glad for writing to let you understand what a amazing encounter my wife's girl developed reading through the blog. She picked up numerous pieces, not to mention what it's like to have an ideal coaching character to get the others completely comprehend various grueling topics. You actually exceeded readers' desires. Thank you for offering the beneficial, trustworthy, informative and also fun tips on this topic to Kate. supreme outlet http://www.supremesoutlet.us.com

moncler outlet, 2020/10/30 04:25

I wish to express my passion for your generosity supporting those people that absolutely need assistance with your concept. Your special commitment to getting the message up and down appeared to be surprisingly practical and has specifically encouraged men and women just like me to attain their endeavors. Your new informative information indicates a lot a person like me and especially to my peers. Thanks a lot; from all of us. moncler outlet http://www.monclers.us.com

cheap jordans, 2020/10/30 04:24

I just wanted to construct a comment to thank you for some of the stunning steps you are giving out on this website. My extended internet research has now been paid with beneficial points to go over with my colleagues. I 'd suppose that most of us visitors actually are really blessed to live in a fabulous network with many lovely people with interesting pointers. I feel truly grateful to have encountered your site and look forward to many more enjoyable minutes reading here. Thanks a lot again for all the details. cheap jordans http://www.cheapjordans.us.com

kd 12, 2020/10/30 04:24

I precisely desired to say thanks yet again. I do not know the things I would have made to happen in the absence of the actual tips and hints shared by you concerning this industry. It had become a real alarming scenario in my view, however , noticing this specialised approach you resolved it made me to leap for fulfillment. Extremely happier for the advice and in addition hope that you are aware of a great job you happen to be putting in educating people using a site. I'm certain you have never come across all of us. kd 12 http://www.kd12.org

yeezy, 2020/10/30 04:24

I together with my pals have been reviewing the best tactics found on your site then all of a sudden I had a terrible suspicion I had not expressed respect to the web site owner for those techniques. All of the women had been totally glad to read them and have now absolutely been making the most of those things. Many thanks for getting considerably thoughtful as well as for finding varieties of really good subjects millions of individuals are really eager to discover. Our own sincere apologies for not saying thanks to earlier. yeezy http://www.yeezyadidas.us

golden goose sneakers, 2020/10/30 04:24

I simply wanted to construct a small remark to thank you for those marvelous ways you are posting on this site. My extensive internet investigation has now been rewarded with useful insight to go over with my contacts. I 'd tell you that many of us readers actually are extremely fortunate to live in a superb network with very many lovely people with great strategies. I feel rather lucky to have discovered your webpages and look forward to really more brilliant minutes reading here. Thanks again for a lot of things. golden goose sneakers http://www.goldengoose-sneakers.us

hermes, 2020/10/27 06:23

My spouse and i felt very glad when Albert managed to conclude his researching with the ideas he grabbed while using the blog. It's not at all simplistic just to continually be giving freely guides that many the rest have been selling. So we already know we have got the writer to be grateful to for this. The main illustrations you have made, the easy website navigation, the relationships you assist to create - it's got many awesome, and it is making our son in addition to our family reckon that the concept is thrilling, and that is unbelievably indispensable. Many thanks for all the pieces! hermes http://www.hermes-handbags.us.com

off white shoes, 2020/10/27 06:23

I precisely desired to say thanks again. I'm not certain the things that I would have undertaken without the type of information revealed by you over that field. It actually was a real troublesome situation for me, however , being able to view a new professional tactic you solved it forced me to cry for joy. I am just happy for your information and as well , have high hopes you recognize what an amazing job that you're doing instructing many others all through your site. Most probably you've never encountered any of us. off white shoes http://www.off-whiteshoes.us.com

authentic jordans, 2020/10/27 06:23

My husband and i ended up being very fortunate Raymond managed to deal with his research from the ideas he came across through the web page. It's not at all simplistic to simply always be giving away guidance most people could have been selling. So we fully understand we have got the writer to thank for that. The explanations you have made, the straightforward site menu, the friendships you will aid to instill - it's all overwhelming, and it's really helping our son and us recognize that that idea is thrilling, which is seriously pressing. Many thanks for the whole lot! authentic jordans http://www.jordansforcheap.us.com

irving shoes, 2020/10/27 06:23

I really wanted to post a simple note to appreciate you for all the superb tactics you are posting on this website. My time consuming internet look up has at the end of the day been rewarded with sensible points to exchange with my friends and family. I 'd assert that we readers actually are rather fortunate to be in a very good place with many special people with helpful opinions. I feel very much lucky to have discovered your weblog and look forward to many more entertaining times reading here. Thank you again for everything. irving shoes http://www.kyrieirving-shoes.us.com

moncler, 2020/10/27 06:23

Thanks for your entire work on this blog. Kim takes pleasure in making time for investigation and it is easy to see why. I notice all about the powerful tactic you deliver functional tips via this web blog and therefore increase response from other ones about this article while our princess is really starting to learn a great deal. Have fun with the rest of the new year. You are conducting a fabulous job. moncler http://www.monclerjacketsoutlet.us.com

giannis antetokounmpo shoes, 2020/10/27 06:23

I would like to point out my appreciation for your generosity giving support to men and women who need help with this important question. Your real dedication to passing the message throughout had become wonderfully invaluable and has always made some individuals much like me to arrive at their dreams. This invaluable key points indicates a whole lot a person like me and far more to my office colleagues. Thanks a lot; from everyone of us. giannis antetokounmpo shoes http://www.giannisantetokounmposhoes.us

hermes, 2020/10/27 06:23

I enjoy you because of your own efforts on this web page. My daughter delights in managing investigation and it is easy to see why. My partner and i know all relating to the powerful way you offer efficient steps via this website and therefore inspire contribution from website visitors on this area while our own girl is undoubtedly learning so much. Enjoy the remaining portion of the new year. You're doing a powerful job. hermes http://www.hermesonlineshop.com

yeezys, 2020/10/27 06:23

I and my friends were actually studying the excellent guidelines from your site and instantly I had a horrible suspicion I never expressed respect to the website owner for those strategies. All of the people happened to be for this reason very interested to see them and have in effect actually been taking pleasure in these things. We appreciate you really being so kind and for choosing this sort of incredibly good subject matter most people are really desirous to be informed on. Our honest apologies for not expressing gratitude to you earlier. yeezys http://www.yeezysus.com

supreme shirt, 2020/10/27 06:23

I simply wanted to write down a message to appreciate you for these fantastic ideas you are placing at this website. My time consuming internet research has now been honored with awesome facts and techniques to go over with my family. I 'd declare that we website visitors are very much lucky to be in a fantastic site with so many wonderful professionals with very helpful tactics. I feel really lucky to have come across your website and look forward to plenty of more pleasurable minutes reading here. Thanks once more for a lot of things. supreme shirt http://www.supremeshirt.us.com

golden goose, 2020/10/27 06:22

I want to show thanks to you just for bailing me out of this type of incident. Right after looking throughout the the net and finding advice that were not beneficial, I was thinking my life was done. Living without the presence of answers to the problems you have sorted out as a result of your blog post is a serious case, and the kind which could have in a negative way affected my career if I had not come across your blog post. Your good understanding and kindness in playing with every item was important. I am not sure what I would have done if I hadn't encountered such a stuff like this. I can at this moment relish my future. Thanks for your time so much for your high quality and effective help. I will not hesitate to endorse your site to any person who desires tips on this subject. golden goose http://www.golden-goose.us

Entrer votre commentaire. La syntaxe wiki est autorisée:
 
slam4/poo/designpattern.txt · Dernière modification: 2017/08/09 16:45 (modification externe)
GNU Free Documentation License 1.3
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0