单例模式学习:
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);
}
}