您好,登錄后才能下訂單哦!
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雙重檢查鎖機制實現(xiàn)
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.使用靜態(tài)內(nèi)置類實現(xiàn)單例模式
public class MyObject{
//內(nèi)部類方式
private static class MyObjectHandler {
private static MyObject mb = new MyObject();
}
private MyObject(){}
public static MyObject getInstance() {
return MyObjectHandler.mb;
}
}
3.使用static代碼塊實現(xiàn)單例模式
public class MyObject{
private static MyObject mb = null;
private MyObject(){}
static {
mb = new MyObject();
}
public static MyObject getInstance() {
return mb;
}
}
4.使用enum枚舉數(shù)據(jù)類型實現(xiàn)單例模式
public enum MyEnum{
connectionFactory;
private Connection connection;
//枚舉類的構(gòu)造方法默認是private的,所以訪問限定符private可以省略不寫
MyEnum {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setURL();
dataSource.setUser();
dataSource.setPassword();
connection = dataSource.getConnection();
}
public Connection getInstance() {
return connection;
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。