Вопрос

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.

Это было полезно?

Решение

Using Deck as the type of the property keeps your CardGameViewController more generic. If you wanted to use a different type of deck in the future, you could simply change that one line of code where the deck is created.

Also, if you simply made that property public, you could then create different CardGameViewControllers with different kinds of decks instead of having a PlayingCardDeckGameViewController and a TarotCardDeckGameViewController and a PinochleCardDeckGameViewController, etc.

In general, using Deck instead of PlayingCardDeck keeps more options open for you and increases the reusability of CardGameViewController.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top