Skip to content

Instantly share code, notes, and snippets.

Created April 23, 2014 06:41
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 anonymous/11204814 to your computer and use it in GitHub Desktop.
Save anonymous/11204814 to your computer and use it in GitHub Desktop.
class Item {
String name
int price
}
trait Trader {
// property
int availableMoney = 0
private int tradesDone = 0
// method
def buy(Item item) {
if (item.price <= availableMoney) {
availableMoney -= item.price
tradesDone += 1
println "${getName()} bought ${item.name}"
}
}
def sell(Item item) {
}
// abstract method
abstract String getName()
}
class Merchant implements Trader {
String name
// 實做抽象方法
String getName() {
return this.name
}
}
def bike = new Item(name: 'big red bike', price: 750)
def paul = new Merchant(name: 'paul')
paul.availableMoney = 2000
paul.buy(bike) // prints "paul bought big red bike"
println paul.availableMoney // 1250
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment