Code Java de l'exemple du pat État (la princesse et la grenouille).

/*
 * 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;

public final class Etat {

    public static void main( String[] args ) {
        Creature1 creature1 = new Creature1();
        creature1.greet();
        creature1.kiss();
        creature1.greet();
        Creature2 creature2 = new Creature2();
        creature2.greet();
        creature2.kiss();
        creature2.greet();
    }
}

final class Creature1 {
    private boolean _isFrog = true;

    public void greet() {
        if (_isFrog) {
            System.out.println("Coââ-coââ!");
        } else {
            System.out.println("Chérie!");
        }
    }

    public void eat() {
        if (_isFrog) {
            System.out.println("moucherons!");
        } else {
            System.out.println("Tarte");
        }
    }

    public void kiss() {
        _isFrog = false;
    }
}

final class Creature2 {
    private State _state = new Frog();

    public void greet() {
        System.out.println(_state.greet());
    }

    public void kiss() {
        _state = new Prince();
    }

    private interface State {
        String greet();
    }

    private class Frog implements State {
        public String greet() {
            return "Coââ-coââ!";
        }
    }

    private class Prince implements State {
        public String greet() {
            return "Chérie!";
        }
    }
}
Modifié le: Saturday 13 October 2018, 08:36