1、单例模式
创建方法1、(最为常用):
public class User{
private static final User INSTANCE = new Uer();
public static User getInstance(){
retrun INSTANCE ;
}
//将构造方法设置为私有
private User(){
}
}
创建方法2、:
public class User{
private static final User INSTANCE ;
static{
INSTANCE = new Uer();
}
public static User getInstance(){
retrun INSTANCE ;
}
//将构造方法设置为私有
private User(){
}
}
创建方法3、: lazyLoading1
加锁是整个方法,效率低不建议
public class User{
private static User INSTANCE ;
public static synchronized User getInstance(){
if(INSTANCE ==null){
INSTANCE = new Uer();
}
retrun INSTANCE ;
}
//将构造方法设置为私有
private User(){
}
}
创建方法4、: lazyLoading2
public class User{
private static voliateUser INSTANCE ;
public static User getInstance(){
if(INSTANCE ==null){
synchronized {
if (INSTANCE==null){
INSTANCE = new Uer();
}
}
retrun INSTANCE ;
}
//将构造方法设置为私有
private User(){
}
}
创建方法5、: 静态内部类
public class User{
//将构造方法设置为私有
private User(){
}
//一个类的静态内部类,在外面那个类被加载的时候,静态内部类是不会被加载的
private static class UserHoler{
private final static User INSTANCE = new User();
}
public static User getInstance(){
return UserHoler.INSTANCE;
}
}
创建方法6、: 枚举类
public enum User{
INSTANCE ;
public void abc(){}
}