0

したがって、私は約10〜15のクラスを持っており(これは時間の経過とともにはるかに多くなる可能性があります)、それらはすべて、それらの中にかなり類似した変数を持っています:

temp
conditions
humidity
load

..そしてそのようなもの。親クラス(抽象)はすべて実行可能であるため、これをより適切に管理するために実装することを検討しています。

それぞれのコンストラクターを呼び出す部分がありますが、それは...ただ悪いことです。

 public ThreadHandler(NH.NHandler NSH, int threadNum){
    this.threadNum=threadNum;
    this.NSH = NSH;
}

public ThreadHandler(OPA.OpaHandler SgeSH, int threadNum){
    this.threadNum=threadNum;
    this.OpaSH = OpaSH;
}

public ThreadHandler(SGE.SgeHandler SgeSH, int threadNum){
    this.threadNum=threadNum;
    this.SgeSH = SgeSH;
}

.....そして15のために

親クラスを実装して単純に行うにはどうすればよいですか?

public ThreadHandler(objectType name, int threadNum){
    //Do stuff
}

助けてくれてありがとう。

4

3 に答える 3

1

abstract classを使用しextendsた別の例がありChildClassます。私はあなたの問題を助けることを願っています。

ParentHandler.java

public abstract ParentHandler<T> {

    public T obj;
    public int threadNum;
    // Declare the common variable here...

    public ParentHandler(T obj, int threadNum) {
        this.threadNum = threadNum;
        this.obj = obj;
    }
}

ChildHandler.java

public class ChildHandler extends ParentHandler<NH.NHandler> {

    public ChildHandler(NH.NHandler nsh, int threadNum) {

        super(nsh, threadNum);
    }
}
于 2012-06-05T02:00:18.007 に答える
1

たとえば、共通のメソッドを持つ IHandler などのインターフェイスを作成する必要があり、すべてのハンドラーはこのインターフェイスを実装する必要があります

public interface IHandler {
      .... declare public methods 
    } 
public NHandler implements IHandler  {
       .... implement all the methods declared in IHandler..
    }
これで、次のものを入れることができますThreadHandler
public ThreadHandler(IHandler  handler, int threadNum){
        .... call the methods
    }

于 2012-06-05T00:59:13.590 に答える
-1

インターフェイスを実装すると、すべての「子」クラスがそれを実装します。次に、インターフェイス型のオブジェクトを宣言し、次のように、何かに基づいて特定のクラスを返すメソッドを作成できます。

    public Interface ITest
    {
        string temp;
        void Test(string param1, string param2);
    }

    public Class Class1 : ITest
    {
        void Test(string param1, string param2)
        {
            // DO STUFF
        }
    }

    public Class Class2 : ITest
    {
        void Test(string param1, string param2)
        {
            // DO STUFF
        }
    }

その後:

    public ITest GetClass(string type)
    {
         switch (type)
         {
             case "class1":     
                   return new Class1();
             case "class2":     
                   return new Class2();
         }  
    }

そして、あなたはそれを次のように呼びます

    ITest obj = GetClass("class1");
    obj.Test();
于 2012-06-04T20:36:27.857 に答える