1:模式:解决一类问题的固定步骤.
需求 :保证一个类中在内存中只有一个对象
(hadoop分布式文件存储系统技术.)
饿汉单例设计模式:
1.私有化本类的构造函数
2,声明本类的引用类型变量.使用 private static 来修饰.并创建本类的对象.
3.提供一个公共的方法来获取本类的对象.
代码:
class Single{private static Single s=new Single();
private Single(){}
public static Single getInStance(){
return s;
}
}
class Demo1{
public static void main(String[] args){
Single s1=Single.getInStance();
Single s2=Single.getInStance();
System.out.println(s1==s2);
}
}
懒汉单例设计模式:
1.私有化本类的构造函数
2,声明本类的引用类型变量.使用 private static 来修饰.但不要创建本类的对象.
3.提供一个公共的方法来获取本类的对象.获取之前先判断是否创建了对象.
class Single{
private static Single s;
private Single(){}
public static Single getInStance(){
private static Single s;
private Single(){}
public static Single getInStance(){
if(s==null){
s=new Single();
}
return s;
}
}
class Demo1{
public static void main(String[] args){
Single s1=Single.getInStance();
Single s2=Single.getInStance();
System.out.println(s1==s2);
}
return s;
}
}
class Demo1{
public static void main(String[] args){
Single s1=Single.getInStance();
Single s2=Single.getInStance();
System.out.println(s1==s2);
}
}
总结:但是懒汉单例设计模式存在线程安全问题.