【发布时间】:2015-03-27 01:24:39
【问题描述】:
我在实现正确的代码时遇到了麻烦。 我有几个使用 ssh 隧道的对象,我不想每次都关闭并打开一个新连接。 所以我实现了单例模式来获取我的连接实例并将它传递给每个对象。 阅读后似乎单例模式不是一种正确的编码方式,但我没有看到任何其他方式重新编码我的类。
实例类:
public class ServerConnection {
String ip = "localhost";
String user = "tom1";
String pass = "1";
int port = 22;
private static Session session;
private ServerConnection() throws JSchException {
try {
JSch jsch = new JSch();
session = jsch.getSession(user, ip, port);
session.setPassword(pass);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
}catch(Exception e){
System.out.println(e);
}
}
public static Session getInstance() throws JSchException {
if (session == null) {
System.out.println("Creation de la connection");
new ServerConnection();
}else{
System.out.println("La connection existe deja");
}
return session;
}
}
我的对象:
public class EchoText implements InterfaceScript
{
/**
*Message to display with the Echo.
*/
String message;
/**
* Params of the test.
*/
String params;
/**
*Result of the test.
*/
String result="Failed";
/**
*Constructor of EchoText.
*/
public void EchoText (){
}
@Override
public String run(String params) {
this.params=params;
treatParameters();
Session session;
try {
//Verify if an instance of the server is running.
session = ServerConnection.getInstance();
//Open a channel to send informations
ChannelExec channel = (ChannelExec) session.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
//Set the command to send
channel.setCommand("cmd /c echo "+this.message);
channel.connect();
// Read the outptut
String msg = null;
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
channel.disconnect();
this.result();
return this.result;
} catch (JSchException | IOException e)
{
System.out.println(e);
return this.result;
}
}
}
【问题讨论】: