Code Java de l'exemple du patron Décorateur (jeu de rôle).

/*
 * Copyright (c)
 * ENSICAEN, École publique d'ingénieurs et centres de recherche, Caen, FRANCE. * https://www.ensicaen.fr * * This file is licenced under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package fr.ensicaen.gl2a.lecture; import java.awt.color.ICC_ColorSpace; public final class Decorateur { public static void main( String[] args ) { Combattant c1 = new Epee(new Arc(new Chevalier())); c1.combattre(); } } abstract class Combattant { abstract void combattre(); } final class Chevalier extends Combattant { @Override void combattre() { System.out.println("Combattre comme un chevalier"); } } final class Mercenaire extends Combattant { @Override void combattre() { System.out.println("Combattre comme un mercenaire"); } } abstract class Arme extends Combattant { private Combattant _component; protected Arme( Combattant component ) { _component = component; } @Override public void combattre() { _component.combattre(); } } final class Epee extends Arme { public Epee( Combattant component ) { super(component); } @Override public void combattre() { super.combattre(); System.out.println(" avec une épée"); } } final class Arc extends Arme { public Arc( Combattant component ) { super(component); } @Override public void combattre() { super.combattre(); System.out.println(" avec un arc"); } }
Modifié le: Saturday 13 October 2018, 08:35