设计模式之单例模式
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; } }
相关文章推荐
- 闲聊设计模式和类
- 好书整理系列之-设计模式:可复用面向对象软件的基础 5
- 好书整理系列之-设计模式:可复用面向对象软件的基础 4
- 好书整理系列之-设计模式:可复用面向对象软件的基础 3
- 好书整理系列之-设计模式:可复用面向对象软件的基础 2
- 好书系列之-设计模式:可复用面向对象软件的基础 1
- 好书整理系列之-设计模式:可复用面向对象软件的基础 5.5
- 设计模式、用Delphi描述-->Abstract Factory模式
- 设计模式、用Delphi描述-->Factory Method模式
- 设计模式、用Delphi实现---->Strategy模式
- 与大虾对话: 领悟设计模式
- 好书整理系列之-设计模式:可复用面向对象软件的基础 6
- 设计模式入门(1)------单件(Singleton)
- 设计模式、用Delphi描述-->Reference Count pattern
- Engine-Collection-Class,一种用来建立可重用企业组件的设计模式
- 好书整理系列之-设计模式:可复用面向对象软件的基础 7
- 好书整理系列之-设计模式:可复用面向对象软件的基础 8
- Jive 中的设计模式
- 设计模式、用Delphi描述-->Visitor模式
- 设计模式、用Delphi实现---->Template Method模式