dragon8997474 2010-07-14 19:53
浏览 56
已采纳

对集合中的对象进行排序和分组

How would you handle grouping different objects?

For example, lets say you have a book of sport cards and you want to organize and spit out data about that book of sport cards. Obviously each sport card should have its own class and be its own object, but how would you group different sets of sprots cards? What if you wanted to see how many cards (and even the cards themselves) that were made by a given manufacturer in a given year?

Should There be a class card_book that organizes each card with functions like

getTotalBySport($sport) // Gets total number of cards within a given sport

getTotalByPrice($min, $max) // Gets total number of cards within a given price range

getCardsBySport($sport) // Get an array (or whatever other container) of cards within a given sport

or should those functions be implemented directly into the cards class?

  • 写回答

3条回答 默认 最新

  • doutang2382 2010-07-14 19:56
    关注

    You would have one class that describes the sports cards. From that class, you'd create objects representing each card, with all of its sundry details.

    You may also want a class that represents a collection of sports cards to, well, manage a collection of sports cards.

    Functions with in the sports card class (called methods in OOP speak) deal with managing the card's details. Functions within the collection class would deal with the collection.

    Edit:

    To expand on this:

    The constructor for the card class would accept parameters to initialize the object when it's created. How you go about this depends on various issues. Since there's likely a lot of data, I would favor an associative array. This would make creating a bunch of objects easier.

    You'd also likely want setter methods for all the info that a card represents, and of course getter methods in order to retrieve that info. Depending on your needs, you may do this for each piece of information, or chunk things up as reasonable. So, for example, maybe one method to add a year's worth of statistics, instead of one method for each particular type of stat. Meanwhile, something like the player's name would have it's own set of methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?