创建控制对象或方法来处理两个对象之间的关系更好吗?

问题描述 投票:0回答:1

假设我有一个游戏,在游戏中允许玩家在设计级别以表格形式/向卖家购买或出售物品的最佳选择,创建另一个类别进行交易,或者每个类别应该拥有自己的买卖方法来处理操作,或者这两个都是错误的:)?

第二种情况如下:

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
    }
}
java oop object-oriented-analysis
1个回答
0
投票

您可以为两者都创建一个抽象类,并扩展该父类并放置相同的内容

逻辑和变量进入此父类,例如,您有moneyitemsPrice

itemCartsPlayer中的[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成为PlayerSeller]的父项>

public class Player extends Parent {

}

public class Seller extends Parent {

}

,以及PlayerSeller中任何一个的用法>

Player p = new Player();
p.buy();
p.sell();

Seller s = new Seller();
s.buy();
s.sell();
© www.soinside.com 2019 - 2024. All rights reserved.