java,单例设计模式,详解

  • 单例设计模式(饿汉式)

 

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) ;
	}
}

 

 

     多例只是单例的一种衍生品,本质上没有区别。

     1对于单例设计模式、多例设计模式更希望理解它设计的出发点:限制对象产生;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值