Code du calcul du prix d'un panier

/*
 * Copyright (c) Régis Clouard
 * 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;

public final class CalculerPrix {
    public static void main( String[] args ) {
        Part[] parts = new Part[3];
        Part motherboard = new Part(300);
        motherboard.setPricePolicy(new PricePolicy(1.45));
        parts[0] = motherboard;

        Part memory = new Part(180);
        memory.setPricePolicy(new PricePolicy(1.27));
        parts[1] = memory;

        Part mouse = new Part(50);
        mouse.setPricePolicy(new PricePolicy(1));
        parts[2] = mouse;

        System.out.println("Prix total : " + totalPrice(parts));
    }

    private static double totalPrice( Part[] parts ) {
        double total = 0.0;
        for (Part p : parts) {
            total += p.getPrice();
        }
        return total;
    }
}

final class Part {
    private double _price;
    private PricePolicy _pricePolicy;

    public Part( double price ) {
        _price = price;
    }

    public void setPricePolicy( PricePolicy pricePolicy ) {
        _pricePolicy = pricePolicy;
    }

    public double getPrice() {
        return _pricePolicy.getPrice(_price);
    }
}

final class PricePolicy {
    private final double _factor;

    public PricePolicy( double factor ) {
        _factor = factor;
    }

    public double getPrice( double price ) {
        return price * _factor;
    }
}
Modifié le: Wednesday 8 November 2017, 18:25