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双重检查锁机制实现
10余年的呼图壁网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。网络营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整呼图壁建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联从事“呼图壁网站设计”,“呼图壁网站推广”以来,每个客户项目都认真落实执行。
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;
}
}