1、懒汉式:
//懒汉式
public class Config {
//3 声明类的静态变量
private static Config cfg;
//1 使用private修饰默认的构造方法
private Config(){}
//2 进行判断,如果对象存在,不再创建对象
//4 为了保证线程同步,改为同步方法
public synchronized static Config getInstance(){
if(cfg == null){
cfg = new Config();
}
return cfg;
}
}
2、饿汉式
//饿汉式
public class Dog {
private static Dog dog = new Dog();
private Dog(){}//尽量写,防止自己创建对象而不是通过 单利创建;
public static Dog getInstance(){
return dog;
}
}