Created
May 29, 2011 16:43
-
-
Save Techmind/997931 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User | |
include Buyer | |
include BuyerWithShotgun | |
end | |
class Buyer | |
private money | |
def canPay(price) | |
money > price | |
end | |
end | |
class BuyerWithShotgun | |
private money | |
private haveShotgun | |
def canPay(price) | |
haveShotgun || money > price | |
end | |
end | |
class ShopContext | |
def buy(user, shop, item) | |
raise ArgumentError unless user.kind_of?(Buyer) | |
raise ArgumentError unless catalog.kind_of?(Shop) | |
if (user.canPay(item.price)) | |
# calling Buyer`s.add which pays honestly, & reduced money amount | |
user.add(item, price) | |
shop.lose(item) | |
end | |
end | |
end | |
class PoorMansShopContext | |
def buy(user, shop, item) | |
raise ArgumentError unless user.kind_of?(BuyerWithShotgun) | |
raise ArgumentError unless shop.kind_of?(Shop) | |
if (user.canPay(item.price)) | |
# calling BuyerWithShotgun`s.add which just shows shotgun & takes item for free | |
user.add(item, price) | |
shop.lose(item) | |
end | |
end | |
end | |
# context call | |
user = new User('Rob') | |
user.setBalance(0) | |
user.haveShotgun(true) | |
nosecurityShop = new PoorMansShop('grocery') | |
# will work as expected, shotgun-way | |
PoorMansShopContext.buy(user, nosecurityShop , 'water') | |
weaponShop = new PawnShop('weapon') | |
# will not work as expected, user still manages to buy | |
ShopContext.buy(user, weaponShop, 'bullets') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment