use sharing to support large unmbers of fine-grained objects efficiently(使用共享对象可有效地支持大量的细粒度的对象)
例子
public class SignInfo { private String key; private String id; private String subject; private String location; public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
public class SignInfoFactory { private static HashMap<String,SignInfo> pool=new HashMap<String,SignInfo>(); public static SignInfo getSignInfo(String key){ SignInfo result=null; if(!pool.containsKey(key)){ System.out.println(key+"-------------建立对象,并放到池中"); result=new SignInfo(); pool.put(key, result); }else{ result=pool.get(key); System.out.println(key+"---------------直接从池中取"); } return result; } }
小知识
public class Client { public static void main(String[] args) { String state1="sub1shanghai1"; String state2="sub1shanghai2"; String state3="sub1shanghai2"; SignInfoFactory.getSignInfo(state1); SignInfoFactory.getSignInfo(state2); long start=System.currentTimeMillis(); for(int i=0;i<100000;i++){ SignInfoFactory.getSignInfo(state3); } long end=System.currentTimeMillis(); System.out.println("total time:"+(end-start)+"ms"); } }
不得不说这是个好东西,但是实际中,需要考虑的东西很多,这个为了解决一些连接问题根据底层硬件以及环境而做出的最好行动,还是需要看背景和实际问题。
我是菜鸟,我在路上。