假设我有一个游戏,在游戏中允许玩家在设计级别以表格形式/向卖家购买或出售物品的最佳选择,创建另一个类别进行交易,或者每个类别应该拥有自己的买卖方法来处理操作,或者这两个都是错误的:)?
第二种情况如下:
public class Player {
privte int money;
// Other fields
List<Integer> itemsPrice = new ArrayList<>();
List<Integer> itemsCart = new ArrayList<>();
public void buy(){
// Add item to itemsCart
// decrease the amount of money
}
public void sell(){
// remove item from itemsCart
// increase the amount of money
}
}
class Seller{
private int money;
List<Integer> itemsPrice = new ArrayList<>();
List<Integer> itemsCart = new ArrayList<>();
public void buy(){
// Add item to itemsCart
// decrease the amount of money
}
public void sell(){
// remove item from itemsCart
// increase the amount of money
}
}
您可以为两者都创建一个抽象类,并扩展该父类并放置相同的内容
逻辑和变量进入此父类,例如,您有money
,itemsPrice
,
itemCarts
和Player
中的[Seller
您都可以将它们添加到父类中
public class Parent {
protected int money;
protected List<Integer> itemsPrice = new ArrayList<>();
protected List<Integer> itemsCart = new ArrayList<>();
public void buy(){
// Add item to itemsCart
// decrease the amount of money
}
public void sell(){
// remove item from itemsCart
// increase the amount of money
}
}
和extends
成为Player
和Seller
]的父项>
public class Player extends Parent { } public class Seller extends Parent { }
,以及
Player
和Seller
中任何一个的用法>Player p = new Player(); p.buy(); p.sell(); Seller s = new Seller(); s.buy(); s.sell();