定义:
单例模式就是一个类只有一个实例变量的一种设计模式,通过使用单例模式,可以节约系统的资源开销,避免共享资源的多重占用等优点。
Java web中的单例模式有
1:数据库连接池就是单例模式
2.Web应用的配置对象的读取,一般也应用单例模式,这个是由于配置文件是共享的资源
3.在Spring中创建的Bean实例默认都是单例模式存在的
运用到项目中:
package com.util;
import com.jcraft.jsch.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class FtpJSch {
private static FtpJSch ftp = null;
private FtpJSch(){
}
public static synchronized FtpJSch getInstance(){
if(ftp == null){
ftp = new FtpJSch();
}
return ftp;
}
private static ChannelSftp sftp = null;
private static Session sshSession = null;
private static Channel channel = null;
public FtpJSch getConnect(String host, String port, String userName, String password)
throws JSchException {
FtpJSch ftp = new FtpJSch();
JSch jsch = new JSch();
//获取sshSession 账号-ip-端口
sshSession = jsch.getSession(userName, host, Integer.parseInt(port));
//添加密码
sshSession.setPassword(password);
Properties sshConfig = new Properties();
//严格主机密钥检查
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
//开启sshSession链接
sshSession.connect();
//获取sftp通道
channel = sshSession.openChannel("sftp");
//开启
channel.connect();
sftp = (ChannelSftp) channel;
return ftp;
}
/**
* @param in 输入流
* @param directory 上传文件的路径
* @return fileName 服务器上文件名
*/
public void upload(InputStream in, String directory, String fileName) throws SftpException {
sftp.cd(directory);
sftp.put(in, fileName);
}
/**
* @param directory 上传文件的路径
* @return fileName 服务器上文件名
*/
public OutputStream upload(String directory, String fileName) throws SftpException {
sftp.cd(directory);
return sftp.put(fileName);
}
/**
* 下载文件
*
* @param directory 要下載的文件路徑
* @param downloadFileName 下载的文件名
* @param os 下载文件输出
*/
public void download(String directory, String downloadFileName, OutputStream os) throws
SftpException {
sftp.cd(directory);
sftp.get(downloadFileName, os);
}
/***
* 下载到本地服务器
* 2018年5月9日
* directory: 指定目录
* downloadFileName :文件名称
* dest: 本地目录
*/
public void download(String directory, String downloadFileName, String dest) throws
SftpException {
sftp.cd(directory);
sftp.get(directory + downloadFileName, dest);
}
public void delete(String path) throws
SftpException {
sftp.rm(path);
}
public void close() {
if (sftp != null) {
sftp.disconnect();
}
if (channel != null) {
channel.disconnect();
}
if (sshSession != null) {
sshSession.disconnect();
}
}
}
调用单例模式的方法:
public class Test{
public static void main(String[] args) {
FtpJSch ftpJSch = FtpJSch.getInstance();
ftpJSch.getConnect(host, port, username, password);
ftpJSch.download(ftpPath, fileName, response.getOutputStream());
ftpJSch.close();
}
}
下面对单件模式的懒汉式与饿汉式进行简单介绍:
1、饿汉式:在程序启动或单件模式类被加载的时候,单件模式实例就已经被创建。
2、懒汉式:当程序第一次访问单件模式实例时才进行创建。
如何选择:如果单件模式实例在系统中经常会被用到,饿汉式是一个不错的选择。
反之如果单件模式在系统中会很少用到或者几乎不会用到,那么懒汉式是一个不错的选择。