gpt4 book ai didi

java - Java中同一个类的继承和组合

转载 作者:行者123 更新时间:2023-12-02 11:59:00 24 4
gpt4 key购买 nike

我在 github 上找到了以下代码:

public class DummySSLSocketFactory extends SSLSocketFactory {

private static final Logger LOG = LoggerFactory.getLogger(DummySSLSocketFactory.class);
private SSLSocketFactory factory;

public DummySSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = new TrustManager[] {new DummyTrustManager()};
sslContext.init(null, trustManagers, new java.security.SecureRandom());
factory = sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeCamelException("Error creating DummySSLSocketFactory: " + e.getMessage(), e);
}
}

/**
* Must provide this getDefault operation for JavaMail to be able to use this factory.
*/
public static SocketFactory getDefault() {
LOG.warn("Camel is using DummySSLSocketFactory as SSLSocketFactory (only to be used for testing purpose)");
return new DummySSLSocketFactory();
}

public String[] getDefaultCipherSuites() {
return factory.getDefaultCipherSuites();
}

public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}

public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return factory.createSocket(socket, host, port, autoClose);
}

public Socket createSocket(String host, int port) throws IOException {
return factory.createSocket(host, port);
}

public Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
throws IOException {
return factory.createSocket(host, port, localAddress, localPort);
}

public Socket createSocket(InetAddress host, int port) throws IOException {
return factory.createSocket(host, port);
}

public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException {
return factory.createSocket(address, port, localAddress, localPort);
}

public Socket createSocket() throws IOException {
// must have this createSocket method
return factory.createSocket();
}

}

类似的实现广泛应用于不同的项目。我试图弄清楚同时使用继承和组合的目的是什么。看起来只要有一个返回 sslContext.getSocketFactory(); 结果的工厂方法就足够了,因为它根本不扩展该类。

最佳答案

我不知道编写这段代码的确切意图是什么,但是在这种类组织中,很明显,使用组合和继承,DummySSLSocketFactory可以使用 protected 方法SSLSocketFactory 中实现,甚至在它上面的类中实现(使用 super)。
这是可能的,因为 DummySSLSocketFactory 具有对其父类 SSLSocketFactory

的引用
 private SSLSocketFactory factory;

在 DummySSLSocketFactory 的构造函数中设置

factory = sslContext.getSocketFactory();

如果没有此引用,您将能够使用 super 访问 SSLSocketLayer,但不能使用更高的类。

关于java - Java中同一个类的继承和组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47395017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com