- 单例设计模式(饿汉式)
- class Singleton { // 编写一个普通类
- private static final Singleton INSTANCE = new Singleton() ;
- private Singleton() {} // 构造方法私有了
- public static Singleton getInstance() {
- return INSTANCE ;
- }
- public void print() {
- System.out.println("www.baidu.com") ;
- }
- }
- public class TestDemo {
- public static void main(String args[]) {
- Singleton inst = null ; // 声明对象
- inst = Singleton.getInstance() ;
- inst.print() ;
- }
- }
构造方法私有化,外部无法产生新的实例化对象,只能够通过类提供的static方法取得唯一的一个对象的引用。
对于单例设计模式有两类:饿汉式(以上代码)、懒汉式。
· 饿汉式:不管程序中是否有对象需要使用此类,那么此类的对象都实例化好;
· 懒汉式:在第一次使用的时候才进行实例化。
- 范例下载:观察懒汉式
- class Singleton { // 编写一个普通类
- private static Singleton instance ;
- private Singleton() {} // 构造方法私有了
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton() ; // 需要的时候进行实例化
- }
- return instance ;
- }
- public void print() {
- System.out.println("www.mldn.cn") ;
- }
- }
- public class TestDemo {
- public static void main(String args[]) {
- Singleton inst = null ; // 声明对象
- inst = Singleton.getInstance() ;
- inst.print() ;
- }
- }
- 多例设计模式
不管是单例设计还是多例设计,本质就一个:构造方法私有化,内部产生实例化对象,只不过单例设计只产生一个,多例设计会产生多个。
例如:现在要求描述一周时间数的类,只能够有七个对象;
例如:例如要求描述性别的类,只能有两个。
范例下载:性别的描述
- class Sex {
- public static final int MALE_CH = 1 ;
- public static final int FEMALE_CH = 2 ;
- private static final Sex MALE = new Sex("男") ;
- private static final Sex FEMALE = new Sex("女") ;
- private String title ;
- private Sex(String title) {
- this.title = title ;
- }
- public static Sex getInstance(int ch) {
- switch(ch) {
- case MALE_CH :
- return MALE ;
- case FEMALE_CH :
- return FEMALE ;
- default :
- return null ;
- }
- }
- public String toString() {
- return this.title ;
- }
- }
- public class TestDemo {
- public static void main(String args[]) {
- Sex sex = Sex.getInstance(Sex.MALE_CH) ;
- System.out.println(sex) ;
- }
- }