所以我有大约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
}
感谢您的帮助。
答案 0 :(得分: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
}
答案 1 :(得分: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);
}
}
答案 2 :(得分:-1)
实现一个接口,每个“child”类都会实现它,然后你可以声明一个接口类型的对象,并创建一个基于某些东西返回特定类的方法,如下所示。
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();