本文共 3896 字,大约阅读时间需要 12 分钟。
key做为一个类别,在多个对象中抽出来相似的做为一个类别,当参数进行传递
public interface IFlyweight { void operation(String extrinsicState);}
public class ConcreteFlyweight implements IFlyweight{ private String intrinsicState; public ConcreteFlyweight(String intrinsicState){ this.intrinsicState = intrinsicState; } @Override public void operation(String extrinsicState) { System.out.println("Object address: " + System.identityHashCode(this)); System.out.println("IntrinsicState: " + this.intrinsicState); System.out.println("ExtrinsicState: " + extrinsicState); }}
public class FlyweightFactory { private static Mappool = new HashMap<>(); public static IFlyweight getFlyweight(String intrinsicState){ if(!pool.containsKey(intrinsicState)){ IFlyweight flyweight = new ConcreteFlyweight(intrinsicState); pool.put(intrinsicState,flyweight); } return pool.get(intrinsicState); }}
public class Test { public static void main(String[] args) { String[] str = { "student","teacher","police"}; for(int i = 0; i < 100;i ++) { IFlyweight iFlyweight = FlyweightFactory.getFlyweight(str[i%3]); iFlyweight.operation("你在干啥"); } }}
public class ConnectionPool { private Vectorpool; private int poolSize = 100; private String url = "jdbc:mysql://localhost:3306/test"; private String username = "root"; private String password = "root"; private String driverClassName = "com.mysql.jdbc.Driver"; public ConnectionPool(){ pool = new Vector (poolSize); try{ Class.forName(driverClassName); for(int i = 0; i < poolSize; i ++){ Connection connection = DriverManager.getConnection(url, username, password); pool.add(connection); } }catch (Exception e){ e.printStackTrace(); } } public synchronized Connection getConnection(){ if(pool.size()>0){ Connection conn = pool.get(0); pool.remove(conn); return conn; } return null; } public synchronized void release(Connection conn){ pool.add(conn); }}
public class Test { public static void main(String[] args) { ConnectionPool pool = new ConnectionPool(); Connection connection = pool.getConnection(); System.out.println(connection); }}
String 中常量池
public class StringTest { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; System.out.println(s1 == s2);//true String s3 = "he" + "llo"; System.out.println(s1 == s3);//true String s4 = "he" + new String("llo"); System.out.println(s1 == s4);//false String s5 = new String("hello"); System.out.println(s1 == s5);//false String s6 = s5.intern(); System.out.println(s1 == s6);//true String s7 = "h"; String s8 = "ello"; String s9 = s7 + s8; System.out.println(s1 == s9);//false String s10 = s9.intern(); System.out.println(s1 == s10); }}
Interger 中缓存-128 到127的缓存池
public class IntegerTest { public static void main(String[] args) { Integer a = Integer.valueOf(100); Integer b = 100; System.out.println(a == b);//true Integer c = Integer.valueOf(1000); Integer d = 1000; System.out.println(c == d);//false }}
转载地址:http://ikjrn.baihongyu.com/