繁体   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