Realistic use case for static factory method?

前端 未结 6 897
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 17:01

I\'m familiar with the idea and benefits of a static factory method, as described in Joshua Bloch\'s Effective Java:

  • Factory methods have names, so you can have mo
6条回答
  •  礼貌的吻别
    2021-02-02 17:53

    Here is one I had to do a while back. At a job interview, I was asked to program a deck of cards where they can be shuffled. Really simple problem. I created:

    Card:
      suit
      rank
    
    Deck:
      card[]
    

    I think what was the distinguishing factor is that there can only 52 cards at all times. So I made the constructor for Card() private and instead create static factory valueOf(suit, rank) This allowed me to cache the 52 cards and make the immutable. It taught many important basic lessons in that books.

    1. immutable
    2. control creation of object
    3. static methods
    4. possibly subclassing and return a card from another source. ( I didn't do this)

    This is similar to Boolean and Byte, except I used a common homework example to show why its important to control the instances. I also created a helper function for deck called newDeck() because I wanted to show an instance where the constructor might not need to be private but it would still be nice to have a helper static factory.

    I hope this helps!

提交回复
热议问题