每日学一个设计模式20——享元模式

享元模式(共享对象,避免浪费)

用处

当需要某个实例时,并不总是通过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();
        }
    }
}

在这里插入图片描述
在这里插入图片描述

控制台打印输出
在这里插入图片描述

总结

  • 减少创建对象的数量,以减少内存占用和提高性能
  • 创建一个缓冲池,如果需要的对象缓冲池中不存在则创建对象并加入缓冲池,否则直接从缓冲池中获取。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑白程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值