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

你需要创建一个接口,比如 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

我有另一个例子使用abstract classand extendsthat to 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

实现一个接口,每个“子”类都会实现它,然后您可以声明一个接口类型的对象并创建一个基于某些东西返回特定类的方法,就像这样。

    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 回答