Strategy

Strategy

Stratégie (patron de conception)

En génie logiciel, le patron stratégie est un patron de conception (design pattern) de type comportemental grâce auquel des algorithmes peuvent être sélectionnés à la volée au cours du temps d'exécution selon certaines conditions, comme les stratégies utilisées en temps de guerre.

Le patron de conception stratégie est utile pour des situations où il est nécessaire de permuter dynamiquement les algorithmes utilisés dans une application. Le patron stratégie est prévu pour fournir des moyens de définir une famille d'algorithmes, encapsuler chacun comme objet, et les rendre interchangeables. Le patron stratégie laisse les algorithmes changer indépendamment des clients qui les emploient.

Utilisation

Dès lors qu'un objet peut effectuer plusieurs traitements différents, dépendant d'une variable ou d'un état.

Exemple en C++

#include <iostream>
using namespace std;
 
class IStrategie
{
public:
	virtual void execute() = 0;
};
 
class AlgorithmeA: public IStrategie
{
public:
	void execute()
	{
		cout << "Traitement A" << endl;
	}
};
 
class AlgorithmeB: public IStrategie
{
public:
	void execute()
	{
		cout << "Traitement B" << endl;
	}
};
 
class AlgorithmeC: public IStrategie
{
public:
	void execute()
	{
		cout << "Traitement C" << endl;
	}
};
 
class Element
{
private:
	IStrategie* strategie;
 
public:
	Element(IStrategie* strategie) : strategie(strategie)
	{
	}
 
	void execute()
	{
		this->strategie->execute();
	}
};
 
int main(int argc, char *argv[])
{
	AlgorithmeA algoA;
	AlgorithmeB algoB;
	AlgorithmeC algoC;
 
	Element elementA(&algoA);
	Element elementB(&algoB);
	Element elementC(&algoC);
 
	elementA.execute(); // L'élément A va effectuer le traitement A
	elementB.execute();	// L'élément B va effectuer le traitement B
	elementC.execute();	// L'élément C va effectuer le traitement C
 
	return (0);
}

Exemple en C#

Des idées semblables amènent à une réalisation à l'aide d'interface.

L'objet qui doit avoir une stratégie adaptable à l'éxécution implémente IStrategie : la même interface que d'autres objets. L'objet principal délègue l'éxécution de la tâche à un autre objet membre qui implémente IStrategie.

L'objet membre étant déclaré dans la classe comme une interface, son implémentation importe peu, on peut donc changer de stratégie à l'éxécution. Cette manière de faire se rapproche du Principe de l'injection de dépendance.

using System;
 
/// <summary> La manière dont le grand général guidera ses troupes</summary>
interface IStrategie {
    void MettreEnOeuvre();
}
 
/// <summary> Ce grand homme qui fera bientôt des choix décisifs </summary>
class SeigneurDeLaGuerre {
 
    /// <summary> une stratégie générique </summary>
    IStrategie _strategie;
 
    /// <summary> comment changer de stratégie </summary>
    public IStrategie Strategie { set { _strategie = value; } }
 
    /// <summary> délégation de la tâche </summary>
    public void PrendreLaVille() {
        _strategie.MettreEnOeuvre();
    }
}
 
class DéfoncerLePontLevisDeFace : IStrategie {
    public void MettreEnOeuvre() {
        Console.WriteLine("Prendre la ville de face en défonçant le pont levis.");
    }
}
class PasserParLaFaceNord : IStrategie {
    public void MettreEnOeuvre() {
        Console.WriteLine("Prendre la ville en escaladant la muraille nord.");
    }
}
class AttendreQueLaVilleSeRende : IStrategie {
    public void MettreEnOeuvre() {
        Console.WriteLine("Attendre qu'il n'y ait plus rien à manger en ville "
            + "et que tout le monde meure de faim.");
    }
}
class SeMarierAvecLaCousineDuDuc : IStrategie {
    public void MettreEnOeuvre() {
        Console.WriteLine("Organiser un mariage avec la cousine du Duc "
            + "alors qu'elle rejoint la ville de retour des baléares "
            + "et inviter toute la ville à une grande fête.");
    }
}
/// <summary> Différentes situations </summary>
enum Météo {
    IlFaitBeau,
    IlYADuBrouillard,
    IlFaitTropChaudPourTravailler,
    IlPleut
}
 
class Program {
    static void Main() {
 
        // notre acteur
        var kevin = new SeigneurDeLaGuerre();
 
        // les aléas du système
        var météo = (Météo)(new Random().Next(0, 3));
 
        // une liaison tardive
        switch (météo) {
            case Météo.IlFaitBeau: 
                kevin.Strategie = new DéfoncerLePontLevisDeFace(); break;
            case Météo.IlYADuBrouillard: 
                kevin.Strategie = new PasserParLaFaceNord(); break;
            case Météo.IlFaitTropChaudPourTravailler:
                kevin.Strategie = new AttendreQueLaVilleSeRende(); break;
            case Météo.IlPleut:
                kevin.Strategie = new SeMarierAvecLaCousineDuDuc(); break;
            default: 
                throw new Exception("Nan finalement seigneur de la guerre c'est "
                    + "pas cool comme job : vous décidez d'aller élever "
                    + "des chêvres dans le Larzac.");
        }
 
        // une éxécution aux petis oignons
        kevin.PrendreLaVille();
    }
}


  • Portail de l’informatique Portail de l’informatique
Ce document provient de « Strat%C3%A9gie (patron de conception) ».

Wikimedia Foundation. 2010.

Contenu soumis à la licence CC-BY-SA. Source : Article Strategy de Wikipédia en français (auteurs)

Игры ⚽ Нужно решить контрольную?

Regardez d'autres dictionnaires:

  • strategy — strategy, tactics, logistics as used in relation to warfare are not always clearly distinguished. Strategy is the art or science involved in the direction of the forces at his disposal by the commander in chief of a belligerent nation or by those …   New Dictionary of Synonyms

  • Strategy — Strat e*gy, n. [Gr. ?: cf. F. strat[ e]gie. See {Stratagem}.] 1. The science of military command, or the science of projecting campaigns and directing great military movements; generalship. [1913 Webster] 2. The use of stratagem or artifice.… …   The Collaborative International Dictionary of English

  • Strategy X — may refer to: * Strategy X (video game), an Atari 2600 game *, the first episode of …   Wikipedia

  • strategy — I noun approach, arrangement, art of war, artifice, battle maneuver, campaign, careful methods, careful plans, consilium, contrivance, course, course of action, cunning, design, devices, engineering, forethought, intrigue, intriguery, invention,… …   Law dictionary

  • strategy — strategy, tactics In war, as in politics and business, strategy is used of an overall plan of action embodying certain principles and objectives, and tactics is used of the detailed means adopted to achieve them. Tactics is normally treated as a… …   Modern English usage

  • strategy — [strat′əjē] n. pl. strategies [Fr stratégie < Gr stratēgia, generalship < stratēgos: see STRATAGEM] 1. a) the science of planning and directing large scale military operations, specif. (as distinguished from TACTICS) of maneuvering forces… …   English World dictionary

  • strategy — (n.) 1810, art of a general, from Fr. stratégie, from Gk. strategia office or command of a general, from strategos general, from stratos multitude, army, expedition, lit. that which is spread out (see STRUCTURE (Cf. structure)) + agos leader,… …   Etymology dictionary

  • strategy — [n] plan of action action, angle, approach, artifice, blueprint*, brainchild*, craft, cunning, design, game, game plan*, gimmick, grand design, layout, maneuvering, method, plan, planning, policy, procedure, program, project, proposition, racket* …   New thesaurus

  • strategy — ► NOUN (pl. strategies) 1) a plan designed to achieve a particular long term aim. 2) the art of planning and directing military activity in a war or battle. Often contrasted with tactics (see TACTIC(Cf. ↑tactician)). DERIVATIVES strategist noun …   English terms dictionary

  • strategy — /strat i jee/, n., pl. strategies. 1. Also, strategics. the science or art of combining and employing the means of war in planning and directing large military movements and operations. 2. the use or an instance of using this science or art. 3.… …   Universalium

  • strategy — The general or specific approach to investing that an individual, institution, or fund manager employs. Bloomberg Financial Dictionary * * * strategy strat‧e‧gy [ˈstrætdʒi] noun strategies PLURALFORM 1. [countable] COMMERCE a plan or series of… …   Financial and business terms

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”