Java将常用方法放在超类中

时间:2015-08-17 12:39:25

标签: java oop polymorphism

我有两个类都使用相同类型的对象作为参数,但是然后在该对象上调用另一个方法来获取另一个对象(获取的对象的类型在两个类中也是不同的),这在整个过程中被广泛使用。不同方法的课程。现在,这些方法中的一些在两个类之间是相同的,所以我认为将它们放在子类中是明智的。但是,由于这些方法依赖于通过对作为构造函数的参数给出的对象调用不同方法而获得的对象,因此我不能只将构造函数从子类复制到超类。我不确定超类如何获得所需的对象。似乎我的潜在超类`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. 
}  

非常感谢你的帮助:))

4 个答案:

答案 0 :(得分:2)

可能有理由继承您的Server类,但是如何获取连接器可能不是子类化的原因。制定策略来处理连接器:

interface ConnectorStrategy {
    Connector retrieveConnector(Conf conf);
}

使用类似

的实现
class ServerOneConnectorStrategy implements ConnectorStrategy {
    public Connector retrieveConnector(Conf conf) {
        return conf.getServerOneConf().getConnector();
    }
}

并在创建时将其传递给Server对象。

或者如果您需要层次结构,请使用template method pattern

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();
    }
}

答案 1 :(得分:1)

如何将Server作为抽象类并从中扩展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{
...
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

将您的共享方法放在超类

class Server() {

      Connector connector; 

      public Server(Conf conf) {
          Configuration config = conf.getServerConf();
          connector = config.getConnector(); // 
      }

      // your methods
}

然后只在子类的构造函数中使用super()调用。他们可以轻松地继承超类的方法而无需再次编写它们。

class ServerOne() extends Server {

    public ServerOne(Conf conf) {
        super(conf);
    }
}