4

I'm following the Stanford online course Developing iOS 7 Apps for iPhone and iPad (link to course in itunes U).

The first assignment asks the students to create some classes(Card, PlayingCard, Deck, PlayingCardDeck) detailed in the notes and update a view controller to display a random card in a deck of playing cards.

Two of the required tasks include:

  1. Add a private property of type Deck * to the CardGameViewController.
  2. Use lazy instantiation to allocate and initialize this property (in the property’s getter) so that it starts off with a full deck of PlayingCards.

I've added the following to my code:

// CardGameViewController.m
#import "PlayingCardDeck.H"

@interface CardGameViewController ()
...
@property (strong, nonatomic) Deck *deck;
@end

@implementation CardGameViewController
- (Deck *)deck
{
    if (!_deck) _deck = [[PlayingCardDeck alloc] init];
    return _deck;
}
...
@end

A hint indicates the following:

  1. Even though the type of the property you must add is required to be a Deck (not PlayingCardDeck) you’ll obviously have to lazily instantiate it using a PlayingCardDeck. This is perfectly legal in object-oriented programming because a PlayingCardDeck inherits from Deck and thus it “is a” Deck. If you are confused by this concept in object-oriented programming, this course may be rather difficult for you.

PlayingCardDeck is a subclass of Deck. I understand that it "is a" Deck.

What I don't understand is why a property of Deck is being used instead of PlyaingCardDeck.

4

1 回答 1

1

使用Deck作为属性的类型使您CardGameViewController更通用。如果您想在将来使用不同类型的卡片组,您只需更改创建卡片组的那一行代码即可。

此外,如果您只是将该属性公开,则可以CardGameViewController使用不同类型的套牌创建不同的 s,而不是使用 aPlayingCardDeckGameViewController和 aTarotCardDeckGameViewController和 aPinochleCardDeckGameViewController等。

通常,使用Deck而不是PlayingCardDeck为您保留更多选项并增加CardGameViewController.

于 2013-11-07T19:32:07.303 回答