public class MyObject{
private static MyObject mb = new MyObject();
private MyObject(){}
public static MyObject getInstance() {
return mb;
}
}
public class MyObject{
private static MyObject mb;
private MyObject(){}
public static MyObject getInstance() {
if (mb == null)
mb = new MyObject();
return mb;
}
}
1.使用DCL双重检查锁机制实现
public class MyObject{
private static MyObject mb;
private MyObject(){}
public static MyObject getInstance() {
if (mb == null) {
synchronized (MyObject.class) {
if (mb == null) {
mb = new MyObject();
}
}
}
return mb;
}
}
2.使用静态内置类实现单例模式
public class MyObject{
//内部类方式
private static class MyObjectHandler {
private static MyObject mb = new MyObject();
}
private MyObject(){}
public static MyObject getInstance() {
return MyObjectHandler.mb;
}
}
3.使用static代码块实现单例模式
public class MyObject{
private static MyObject mb = null;
private MyObject(){}
static {
mb = new MyObject();
}
public static MyObject getInstance() {
return mb;
}
}
4.使用enum枚举数据类型实现单例模式
public enum MyEnum{
connectionFactory;
private Connection connection;
//枚举类的构造方法默认是private的,所以访问限定符private可以省略不写
MyEnum {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setURL();
dataSource.setUser();
dataSource.setPassword();
connection = dataSource.getConnection();
}
public Connection getInstance() {
return connection;
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。