1

first of all let me say that this is not so much a question of how to get it to work, it is more a question of whether this is good practice or not.

I want to implement a deck of cards (As seen in a lot of games, for example TCG games), with a custom shuffle() method... For now it uses a standard library method, but that may change in the future.

The code:

package model;

import java.util.Collections;
import java.util.Stack;

/**
 *
 * @author Frank
*/
public class Deck<T> extends Stack<T> {
    public void shuffle() {
        Collections.shuffle(this);
    }
}

Current code where I use it:

private Deck<Card> deck;

Just wondering if this is good practice, eager to hear answers.

4

2 に答える 2

3

いいえ、これは良い習慣ではありません。Deckクラスにはが含まれている必要がありますが、StackであってはなりませStack

Stackとにかく欲しいかどうかわかりません。あなたが望むArrayList<Card>か、それに似たものである可能性が高いです。

于 2013-03-28T15:53:05.597 に答える
0

ここでは、継承ではなく委任を使用することをお勧めします。スタックを拡張すると、スタックを永遠に使い続けることになりますが、委譲を使用すると、スタックを別のものに簡単に置き換えることができます。

さらに、通常、コレクションを拡張することはベスト プラクティスではありません。Java 8 では、コレクションに多くの新しい機能が導入され、実装やロジックが壊れる可能性があります。

于 2013-03-28T15:56:11.797 に答える