享元模式(共享对象,避免浪费)
用处
当需要某个实例时,并不总是通过new关键词来生成实例,而是尽量公用已经存在的实例。
角色
- Flyweight(轻量级)
按照通常方式编写程序会导致程序变重,所以如果能够共享实例会比较好,而Flyweight角色表示的就是那些实例会被共享的类。 - FlyweightFactory(轻量级工厂)
该角色是生成Flyweight角色的工厂。在工厂中生成Flyweight角色可以实现共享实例。 - Client(请求者)
该角色使用FlyweightFactory角色。
类图
由类图可知
- FlyweightFactory中聚合了Flyweight,想要获取实例的时候,只需要调用getFlyweight函数即可,不需要new实例。
举例
public class Main {
public static void main(String[] args) {
BigString bs = new BigString("223");
bs.print();
}
}
class BigChar{
private char charname;
private String fontdata;
public BigChar(char charname){
this.charname = charname;
try{
BufferedReader reader = new BufferedReader(new FileReader("big"+charname+".txt"));
String line;
StringBuffer buf = new StringBuffer();
while((line = reader.readLine()) != null){
buf.append(line);
buf.append("\n");
}
this.fontdata = buf.toString();
}catch(IOException e){
this.fontdata = charname + "?";
}
}
public void print(){
System.out.println(fontdata);
}
}
class BigCharFactory{
private HashMap pool = new HashMap();
private static BigCharFactory singleton = new BigCharFactory();
private BigCharFactory(){
}
public static BigCharFactory getInstance(){
return singleton;
}
public synchronized BigChar getBigChar(char charname){
BigChar bc = (BigChar) pool.get(" "+charname);
if(bc == null){
bc = new BigChar(charname);
pool.put(" "+ charname,bc);
}
return bc;
}
}
class BigString{
private BigChar[] bigchars;
public BigString(String string){
bigchars = new BigChar[string.length()];
BigCharFactory factory = BigCharFactory.getInstance();
for(int i = 0;i<bigchars.length; i++){
bigchars[i] = factory.getBigChar(string.charAt(i));
}
}
public void print(){
for(int i = 0 ;i<bigchars.length;i++){
bigchars[i].print();
}
}
}
控制台打印输出
总结
- 减少创建对象的数量,以减少内存占用和提高性能
- 创建一个缓冲池,如果需要的对象缓冲池中不存在则创建对象并加入缓冲池,否则直接从缓冲池中获取。