java单例使用示例
/** * 立即加载/饿汉模式
*/
public class StarvingModelSingleton {
private static StarvingModelSingleton instance = new StarvingModelSingleton();
private StarvingModelSingleton() {
}
public static StarvingModelSingleton getInstance() {
return instance;
}
public void doSomeThing() {
System.out.println(">>> StarvingModelSingleton do some things");
}
}
2、延迟加载/懒汉模式
/** * 延迟加载/懒汉模式
*/
public class SlackerModelSingleton {
private static SlackerModelSingleton instance;
private SlackerModelSingleton() {
}
public static SlackerModelSingleton getInstance() {
if (instance == null) {
synchronized (SlackerModelSingleton.class) {
if (instance == null) {
instance = new SlackerModelSingleton();
}
}
}
return instance;
}
public void doSomeThing() {
System.out.println(">>> SlackerModelSingleton do some things");
}
}
3、用Enum实现单例示例
import java.sql.Connection;import java.sql.DriverManager;
/**
* 用Enum实现示例
*/
public class EnumModelSingleton {
public static Connection getInstance() {
return EnumSingleton.SingletonFactory.getConnection();
}
public enum EnumSingleton {
SingletonFactory;
private Connection connection;
//枚举
private EnumSingleton() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "root", "123456");
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
}
}
使用示例
import org.junit.Test;import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SingletonTest {
@Test
public void test1() throws SQLException {
StarvingModelSingleton.getInstance().doSomeThing();
SlackerModelSingleton.getInstance().doSomeThing();
Connection connection = EnumModelSingleton.getInstance();
PreparedStatement preparedStatement = connection.prepareStatement("select * from t_user");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String userName = resultSet.getString("name");
System.out.println(">>> " + userName);
}
resultSet.close();
connection.close();
}
}
以上是 java单例使用示例 的全部内容, 来源链接: utcz.com/z/513128.html