您的位置:首页 > 编程语言 > Java开发

Java学习笔记 —— 12

2014-11-04 16:41 204 查看


23种设计模式

单例的设计模式:

饿汉式

1、解决的问题:使一个类只能够创建一个对象。

2、如何实现。如下:

public class TestSingleton {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}

}
//只能创建Singleton的单个实例
class Singleton {
//1、私有化构造器:使得在类的外部不能使用此构造器
private Singleton() {
super();
// TODO Auto-generated constructor stub
}

//2、在类的内部创建一个类的实例
private static Singleton instance = new Singleton();
//3、私有化此对象,通过公共的方法调用
//4、此公共地方法,只能通过类来调用,因为数组为static的,同时类的实例也必须为static声明的。
public static Singleton getInstance() {
return instance;
}

}


懒汉式

//存在线程安全问题。
class Singleton1 {

//1、私有化构造器:使得在类的外部不能使用此构造器
private Singleton1() {
super();
// TODO Auto-generated constructor stub
}

//2、在类的内部创建一个类的实例
private static Singleton1 instance = null;

//3、
public static Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}

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