我有两个类,它们都以相同类型的对象作为参数,但随后调用该对象上的不同方法来获得另一个对象(所获得的对象的类型在两个类中也不同),这些对象在不同方法的类中被广泛使用。现在,其中一些方法在两个类之间是相同的,所以我认为将它们放在子类中是明智的。但是,由于这些方法依赖于通过调用作为构造函数参数的对象上的不同方法而获得的对象,所以我不能仅仅将构造函数从子类复制到超类。我不知道超类如何获得所需的对象。我的潜在超类Server似乎依赖于它的子类,这听起来甚至是错误的。
下面是问题的说明代码:
class ServerOne() {
Connector connector;
public ServerOne(Conf conf) {
Conf.ServerOneConf config = conf.getServerOneConf();
connector = config.getConnector(); //
}
// a lot of methods that use connector
}
class ServerTwo() {
Connector connector;
public ServerTwo(Conf conf) {
Conf.ServerTwoConf config = conf.getServerTwoConf(); // notice that it uses a different method for obtaining the configuration. Also, the obtained object is of a different type than the configuration object that was obtained in the ServerOne constructor.
connector = config.getConnector();
}
// a lot of methods that use connector
}
class Server() {
// would like to implement some common methods that use connector.
// need to get an instance of the Connector to this class.
} 非常感谢你的帮助:)
发布于 2015-08-17 12:54:53
可能有理由对您的Server类进行子类分类,但是如何获得连接器可能不是子类化的原因。制定一种策略来处理获得连接器的问题:
interface ConnectorStrategy {
Connector retrieveConnector(Conf conf);
}有类似的实现
class ServerOneConnectorStrategy implements ConnectorStrategy {
public Connector retrieveConnector(Conf conf) {
return conf.getServerOneConf().getConnector();
}
}并在创建服务器对象时将其传递给服务器对象。
或者,如果需要层次结构,请使用模板法模式
abstract class Server {
abstract Connector retrieveConnector(Conf conf);
void initializeConnector(Conf conf) {
...
connector = retrieveConnector(conf);
}
...
}
class ServerOne extends Server {
public Connector retrieveConnector(Conf conf) {
return conf.getServerOneConf().getConnector();
}
}发布于 2015-08-17 12:44:10
如何使服务器作为一个抽象类,并从它扩展ServerOne和ServerTwo。
如下所示:
public abstract class Server() {
Connector connector;
public Server() {
Configuration config = conf.getServerTwoConf();
connector = config.getConnector();
}
...
}
class ServerOne() extends Server{
...
}
class ServerTwo() extends Server{
...
}发布于 2015-08-17 12:44:04
这是扩展超类的完美案例。在这两个构造函数中填充的对象具有相同的类型--而不是相同的数据。创建ServerOne时,它将以当前的方式填充超类中的对象。然后,超类中的常用方法现在可以对已填充的对象进行操作。
https://stackoverflow.com/questions/32050658
复制相似问题