3

次のサンプル状況を検討してください。

public abstract class Parent
{
    private ByteBuffer buffer;

    /* Some default method implementations, interacting with buffer */

    public static Parent allocate(int len)
    {
        // I want to provide a default implementation of this -- something like:
        Parent p = new Parent();
        p.buffer = ByteBuffer.allocate(len);
        return p;
    }
}

public class Child extends Parent
{
    /* ... */
}

public class App
{
    public static void main(String[] args)
    {
        // I want to ultimately do something like:
        Child c = Child.allocate(10);
        // Which would create a new child with its buffer initialized.
    }
}

new Parent()明らかに、親は抽象的であるため、これを行うことはできません ( ) が、実際には親は必要ありません。このメソッドをサブクラスに自動的に提供したい。

.allocate()別の可視コンストラクターを追加する代わりに、「静的コンストラクター」アプローチを使用することをお勧めします。

このデフォルトの実装をParentクラスに配置する方法はありますか?それとも、各サブクラスに同じコードを含める必要がありますか?

別のオプションは、親から「抽象」を取り除くことだと思いますが、抽象的に適合します-親タイプのオブジェクトは決して必要ありません。

前もって感謝します。

4

1 に答える 1

5

標準 JDK の Buffer クラスのコレクションを調べると、各特殊化 (ByteBuffer、CharBuffer、DoubleBuffer など) ごとに独自の静的allocateメソッドが定義されていることがわかります。すべてが共通の基本クラスから継承されないのには理由があります - 静的メソッドは継承されません! 代わりに、それらが定義されているクラスに関連付けられ、クラス レベルの変数にのみアクセスできます。

達成しようとしていることのより良いパターンは、ビルダー/ファクトリー パターンです。これらのパターンを実装する方法の例については、JAX-RSResponseクラスまたはDocumentBuilderFactoryクラスを調べることができます。

于 2013-03-12T05:51:00.380 に答える