Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - How To Separate Class Holding Records from Classes That Use It?

I'm creating a console-based game and I'm having trouble deciding on how to properly structure my classes. Say I have the following classes:

Records (Holds records and deals with adding, removing, etc.)

public class Records {
    private Map<String, Player> records = new HashMap<>();

    public Player getByName(String name) {...}
    public void add(String playerName) {...}
    public void remove(String name) {...}
    ... etc ...
    public String getDetails() {...Return record details as string...}

Game (Provides functionality to in-game menu options)

public class Game {
    private Player currentPlayer;
    private Records records;

    public Game(Records records) {
        this.records = records;
    }

    public Player getCurrentPlayer() {...return currentPlayer...}
    public Player getNextPlayer() {...return nextPlayer...}
    ... etc ...
    public String getPlayerDetails() {
        return records.getDetails(); <-- Feels like unnecessary code / repetition?
    }

ViewPlayerDetailsOption (Using the command pattern with the console menu. When the player selects this option in the menu, execute() is called)

public class ViewGameInformationOption extends Option {
    public ViewGameInformationOption(String description, /*Reference to Records or Game?*/) {
        super(description);
    }

    @Override
    public void execute() {}
}

To me it feels like the getPlayerDeatils() method of the Game class is just a copy and paste of the getDetails() method in the Records class, but at the same time I don't think it's right to expose the Records class to the ViewPlayerDetailsOption (or any similar class for that matter).

Any advice on a better way to go about this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...