黑马程序员技术交流社区
标题:
懒汉式单例设计模式的多种形式
[打印本页]
作者:
songyu
时间:
2015-6-5 20:12
标题:
懒汉式单例设计模式的多种形式
package cn.itcast9;
import java.util.Vector;
/*
* 设计一个单例的Person
* 懒汉式单例设计模式
*/
public class Person {
//定义本类类型成员变量,用于记录这个单例对象
//由于被静态方法访问,所以使用static修饰
//为了防止外界改变属性值,使用private修饰
private static Person p;
//构造方法私有化
private Person(){}
// //提供静态公共的返回对象实例的方法
// //标准的获取实例对象的方式
public static Person getInstance() {
if(p==null) {
p = new Person();
}
return p;
}
// //考虑线程安全问题
// public static Person getInstance() {
// synchronized (Demo.LOCK) {
// if(p==null) {
// p = new Person();
// }
// }
// return p;
// }
// //考虑线程安全问题
// public static synchronized Person getInstance() {
// if(p==null) {
// p = new Person();
// }
// return p;
// }
// //考虑线程安全问题,有考虑效率问题
// public static Person getInstance() {
//
// if(p==null) {
// synchronized (Demo.LOCK) {
// if(p==null) {
// p = new Person();
// }
// }
// }
//
// return p;
// }
}
复制代码
package cn.itcast;
/*
* 单例设计模式:
* 内存中有且只有一个对象
*/
public class Demo {
public static final Object LOCK = new Object();
public static void main(String[] args) {
// Person p = new Person();
// Person p2 = new Person();
// System.out.println(p==p2);
Person instance = Person.getInstance();
Person instance2 = Person.getInstance();
System.out.println(instance==instance2);
}
}
复制代码
作者:
嘎路的米
时间:
2015-6-6 07:40
学习到了
作者:
zuoyou
时间:
2015-6-6 12:24
学习,,,
作者:
wuyusi
时间:
2015-6-6 20:27
学些了。。。
作者:
小车车
时间:
2015-6-6 21:08
学习一下!
作者:
路途遥远
时间:
2015-6-6 21:53
学习了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2