单例模式学习及控制实例化对象个数

单例模式学习:
package com.amaker.single;

import java.util.HashMap;
import java.util.Map;

public class People {
//===============================================================
//标准的单例
private static People p = null;
private People(){

}

public static People getInstance(){
if(p==null){
p = new People();
}
return p;
}
//===============================================================
//利用缓存的单例
private static Map<String,People> map = new HashMap<String,People>();
public static People getInstance2(){
People p = map.get("one");
if(p==null){
p = new People();
map.put("one", p);
}
return p;
}
//===============================================================
//实例化三个或更多实例,可以按要求实例化对象个数,如下面的count可以从配置文件中读取
private static int number = 1;
private static int count = 3;
public static People getInstance3(){
p = map.get(number+"");
if(p==null){
p = new People();
map.put(number+"", p);
}
number++;
if(number>count){
number = 1;
}
return p;
}
}


package com.amaker.client;

import com.amaker.single.People;

public class Test {
public static void main(String[] args) {
//单例测试:
/*People p1 = People.getInstance();
System.out.println("p=="+p1);

People p2 = People.getInstance();
System.out.println("p=="+p2);

People p3 = People.getInstance();
System.out.println("p=="+p3);
*/

//缓存测试:
/*People p1 = People.getInstance2();
System.out.println("p=="+p1);

People p2 = People.getInstance2();
System.out.println("p=="+p2);

People p3 = People.getInstance2();
System.out.println("p=="+p3);*/

//控制对象的个数,暂时实例化三个对象
People p1 = People.getInstance3();
System.out.println("p=="+p1);

People p2 = People.getInstance3();
System.out.println("p=="+p2);

People p3 = People.getInstance3();
System.out.println("p=="+p3);

People p4 = People.getInstance3();
System.out.println("p=="+p4);

People p5 = People.getInstance3();
System.out.println("p=="+p5);

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值