您的位置:首页 > 其它

设计模式之单例模式

2016-08-15 21:56 169 查看
package cn.edu.singleton;

public class 单例模式 {
public static void main(String[] args) {
Box info1 = Box.getInfo();
Box info2 = Box.getInfo();
System.out.println(info1 == info2); //测试是否同一个实例  true

Dog dog1 = Dog.getInfo();
Dog dog2 = Dog.getInfo();
System.out.println(dog1 == dog2);//测试是否同一个实例  true
}
}


单例模式有以下特点:  1,在某个类中只存在一个对象实例   2,单例类必须自己创建自己的唯一实例。  3,单例类必须给所有其他对象提供这一实例。



//饿汉式
class Box{
//1,私有化构造器
private Box(){};
//2,指向自己实例的静态私有引用
private static Box box = new Box();
//3,以自己实例为返回值的静态公有方法(暴漏给其他对象使用)
public static Box getInfo(){
return box;
}
}


//懒汉式
class Dog{
//1,私有化构造器
private Dog(){};
//2,指向自己实例的静态私有引用
private static Dog dog = null;
//3,以自己实例为返回值的静态公有方法(需考虑线程安全问题)
public synchronized static Dog getInfo(){
if (dog == null) {
dog = new Dog();
}
return dog;
}
}










                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息