Created
April 23, 2014 06:41
-
-
Save anonymous/11204814 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 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