Я сталкиваюсь с проблемой реализации правильного кода. У меня есть несколько объектов, которые используют туннель ssh, и я не хочу закрывать и открывать новое соединение каждый раз. Итак, я применил singleton pattern, чтобы получить экземпляр моего соединения, и передаю его каждому объекту. После чтения Кажется, что одноэлементный шаблон не является правильным способом кодирования, но я не вижу другого способа перекодировки моих классов.Одно соединение для нескольких объектов
Instance Класс:
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;
}
}
}