samedi 21 mai 2016

A singleton class to design a generic deck of card?

I'm reading the famous cracking the coding interview book and I'm now in a chapter about OOD (Object Oriented Design) with this problem :

design the data structures for a generic deck of cards. Explain how you would subclass the data structures to implement blackjack.

I want to show you here a code that I didn't understand well :

public enum Suit { 
    Club (0),
    Diamond (1),
    Heart (2),
    Spade (3);

    private int value;
    private Suit(int v) {
    value = v;
    }

    public int getValue() {
    return value;
    }

    public static Suit getSuitFromValue(int value) {
    switch (value) {
    case 0:
        return Suit.Club;
    case 1:
        return Suit.Diamond;
    case 2:
        return Suit.Heart;
    case 3: 
        return Suit.Spade;
    default:
            return null;
    }
   }
  }

I'm discovering know the design patterns and I met some difficulties to recognize them in codes. But, when we see a private constructor like in this example, it absolutely means that we want to implement the singleton pattern to have an unique instance of this class, no? Which I found logical, because in one Deck, we have only one suit of each type (diamond, heart...).

So, if (I don't know if there is another cases when the constructor is private), this class is a singleton :

  • Why the value is only private int and not private static int??
  • Why there is no "new " operator in that class? We should at least instanciate a suite to be able to use it no? So, we should have something like : return new Suit.Heart; if (hear !=null)
  • I think it's a BIG problem if a singleton class isn't thread safe no? Because we have to do something to deal with two threads access to the class at the same time. Something like eager instanciation or Double-checked locking with volatile keyword and synchronized only for the first instanciation... I mean, there is many technics to do that, but if we do nothing for that, it can become very bad in term of OOD and performance, no?

Thank you if you can help me to understand better these points

Aucun commentaire:

Enregistrer un commentaire