dimanche 30 juillet 2017

Is this a correct implementation of the Strategy pattern?

Below is the implementation in PHP. I aim to have a different coupon code and a different discount returned, based on the type of book (vintage or new).

<?php

interface BookOffer {
    function generateCoupon();
    function generateDiscount();
}


class VintageBookOffer implements BookOffer {
    function generateCoupon() {
        return "VINTAGECOUPONCODE";
    }

    function generateDiscount() {
        return 10.0;
    }
}


class NewBookOffer implements BookOffer {
    function generateCoupon() {
        return "NEWBOOKCOUPONCODE";
    }

    function generateDiscount() {
        return 5.0;
    }
}


class OfferGenerator {

    function generateOffer($bookType) {

        if($bookType == "vintage") {
            $bookObject = new VintageBookOffer();
        }
        else if($bookType == "newbook") {
            $bookObject = new NewBookOffer();
        }

        return $bookObject;
    }
}


$bookType1 = "vintage";
$bookType2 = "newbook";


$offerGenerator = new OfferGenerator();
$bookOffer1 = $offerGenerator->generateOffer($bookType1);
$bookOffer2 = $offerGenerator->generateOffer($bookType2);


echo "You chose book type " . $bookType1 . ". Your coupon code is " . $bookOffer1->generateDiscount() . ", and your discount is " . $bookOffer1->generateCoupon();

echo "You chose book type " . $bookType2 . ". Your coupon code is " . $bookOffer2->generateDiscount() . ", and your discount is " . $bookOffer2->generateCoupon();

?>

Does this look correct? I believe it is. But any feedback from the community would be welcome. The only reason I think it might be incorrect is because it does not use type hinting, which is frequently seen in the Strategy Pattern.

Aucun commentaire:

Enregistrer un commentaire