设计模式-享元模式

享元模式

用于减少创建对象的数量 如String


/**
 * @USER: lynn
 * @DATE: 2020/4/26
 **/
public class 享元模式 {
    public static void main(String[] args) {
        字符串 string1 = 对象工厂.getChars("a");
        string1.print();
        字符串 string2 = 对象工厂.getChars("a");
        string2.print();
        字符串 string3 = 对象工厂.getChars("b");
        string3.print();
    }
}
interface 对象{
    public void print();
}
class 字符串 implements 对象{
    String chars;

    public 字符串(String chars) {
        this.chars = chars;
    }

    public String getChars() {
        return chars;
    }

    public void setChars(String chars) {
        this.chars = chars;
    }

    @Override
    public void print() {
        System.out.println(chars);
    }
}

class 对象工厂{
    private static final HashMap<String,字符串> 字符串对象池 = new HashMap<>();

    public static 字符串 getChars(String chars){
        字符串 字符串对象 = 字符串对象池.get(chars);

        if (字符串对象 == null){
            字符串对象 = new 字符串(chars);
            字符串对象池.put(chars,字符串对象);
            System.out.println("向字符串对象池插入一个对象:"+字符串对象.toString());
        }
        return 字符串对象;
    }
}
  • 使用场景
    • 系统中有大量相似对象
    • 缓冲池场景

更多请访问Github主页 Github/Cynaith

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。