首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java将常用方法放入超类中

Java将常用方法放入超类中
EN

Stack Overflow用户
提问于 2015-08-17 12:39:24
回答 4查看 529关注 0票数 2

我有两个类,它们都以相同类型的对象作为参数,但随后调用该对象上的不同方法来获得另一个对象(所获得的对象的类型在两个类中也不同),这些对象在不同方法的类中被广泛使用。现在,其中一些方法在两个类之间是相同的,所以我认为将它们放在子类中是明智的。但是,由于这些方法依赖于通过调用作为构造函数参数的对象上的不同方法而获得的对象,所以我不能仅仅将构造函数从子类复制到超类。我不知道超类如何获得所需的对象。我的潜在超类Server似乎依赖于它的子类,这听起来甚至是错误的。

下面是问题的说明代码:

代码语言:javascript
复制
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. 
}  

非常感谢你的帮助:)

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-08-17 12:54:53

可能有理由对您的Server类进行子类分类,但是如何获得连接器可能不是子类化的原因。制定一种策略来处理获得连接器的问题:

代码语言:javascript
复制
interface ConnectorStrategy {
    Connector retrieveConnector(Conf conf);
}

有类似的实现

代码语言:javascript
复制
class ServerOneConnectorStrategy implements ConnectorStrategy {
    public Connector retrieveConnector(Conf conf) {
        return conf.getServerOneConf().getConnector();
    }
}

并在创建服务器对象时将其传递给服务器对象。

或者,如果需要层次结构,请使用模板法模式

代码语言:javascript
复制
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();
    }
}
票数 2
EN

Stack Overflow用户

发布于 2015-08-17 12:44:10

如何使服务器作为一个抽象类,并从它扩展ServerOne和ServerTwo。

如下所示:

代码语言:javascript
复制
public abstract class Server() {
   Connector connector;
   public Server() {
      Configuration config = conf.getServerTwoConf();
      connector = config.getConnector();
   }
...
}  

class ServerOne() extends Server{
...
}

class ServerTwo() extends Server{
...
}
票数 1
EN

Stack Overflow用户

发布于 2015-08-17 12:44:04

这是扩展超类的完美案例。在这两个构造函数中填充的对象具有相同的类型--而不是相同的数据。创建ServerOne时,它将以当前的方式填充超类中的对象。然后,超类中的常用方法现在可以对已填充的对象进行操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32050658

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档