【发布时间】:2011-03-06 03:24:32
【问题描述】:
我正在用 Java 开发一个服务器应用程序。服务器需要两种类型的服务器类。这些类有一些共同的方法,这些方法中的代码完全相同。所以我创建了一个包含所有共享代码的抽象超类,两个类都继承了它。但是,代码的某些部分需要子类进行精确化。我的意思是超类“依赖”子类方法。
这是我的意思的纯化示例:
public abstract class AbstractServer
{
public void loadConfig(String configPath)
{
//Load the configuration file.
//This code is exactly the same for subclasses.
}
public void startRMI(int port)
{
//Create an empty RMI registry.
//This part also need to be identical.
//Here' where the superclass "rely" on subclasses.
fillRegistry(); //Call the method overwritten by subclasses.
}
/**
Bind remote objects in the RMI registry
*/
protected abstract void fillRegistry(); //This method will be overriten by subclasses.
}
我觉得这样做真的很糟糕,但我找不到另一种更清洁的方法。
所以,我想要的是一些关于如何让它变得更好的建议。
谢谢,抱歉我的英语不好。
【问题讨论】:
-
对于初学者来说,我会让 fillRegistry() 受保护,除非它需要在外部调用并且你应该在 SuperClass 的类声明中添加抽象(我觉得最好将其命名为 ServerBase 或 AbstractServer 或其他东西像那样)
-
并且超类必须是抽象的,但除此之外并使方法受到保护,我认为设计没有任何问题。
-
好的,因为我找到了一篇关于 Swing API 的文章。而且作者说JComponent依赖子类的“paintComponent”方法是一件坏事。所以我想知道这样做是否有那么糟糕。
-
总体上没问题,但你应该将 startRMI 方法设为 final 以防止行为在子类中被覆盖
标签: java oop inheritance software-design