簡體   English   中英

實施兒童班的好方法

[英]Good way to implement a child class

因此,我大約有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
}

謝謝你的幫助。

您需要創建一個接口,例如,具有通用方法的IHandler,所有處理程序都應實現此接口

public interface IHandler {
      .... declare public methods 
    } 
public NHandler implements IHandler  {
       .... implement all the methods declared in IHandler..
    }
現在,您可以在ThreadHandler擁有以下ThreadHandler
 public ThreadHandler(IHandler handler, int threadNum){ .... call the methods } 

我還有另一個使用abstract class示例,並將其extendsChildClass 希望對您有幫助。

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);
    }
}

實現一個接口,每個“子”類都將實現它,然后可以聲明該接口類型的對象,並創建一個基於諸如此類的方法返回especific類的方法。

    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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM