Skip to content

Instantly share code, notes, and snippets.

@Techmind
Created May 29, 2011 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Techmind/997931 to your computer and use it in GitHub Desktop.
Save Techmind/997931 to your computer and use it in GitHub Desktop.
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