欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

设计模式——共享模式

程序员文章站 2022-03-25 16:17:20
共享模式_共享对象,避免内存浪费(避免重复创建相同的对象) 附录 github.com/maikec/patt… 个人GitHub设计模式案例 声明 引用该文档请注明出处 ......

共享模式_共享对象,避免内存浪费(避免重复创建相同的对象)

设计模式——共享模式

/**
 * 需要被共享的对象
 * @author maikec
 * @date 2019/5/17
 */
public class flyweight {
    private string name;
    public flyweight(string name){
        this.name = name;
    }

    public string getname() {
        return name;
    }
}

/**
 * @author maikec
 * @date 2019/5/17
 */
public class flyweightfactory {
    private static flyweightfactory ourinstance = new flyweightfactory();
    @getter
    private final map<string, flyweight> pool = collections.synchronizedmap( new hashmap<>(  ) );

    public static flyweightfactory getinstance() {
        return ourinstance;
    }

    private flyweightfactory() {
    }

    public flyweight getflyweight(string flyweightname){
        if (pool.containskey( flyweightname )){
            return pool.get( flyweightname );
        }else{
            flyweight flyweight = new flyweight( flyweightname );
            pool.putifabsent( flyweightname,flyweight );
            return flyweight;
        }
    }
}

/**
 * @author maikec
 * @date 2019/5/17
 */
public class flyweightdemo {
    public static void main(string[] args) {
        flyweightfactory instance = flyweightfactory.getinstance();
        system.out.println( instance.getflyweight( "flyweight" ).getname() );
        system.out.println( instance.getflyweight( "flyweight" ).getname() );

        system.out.println( instance.getflyweight( "flyweight1" ).getname() );

        // 需要配置虚拟机 -ea 参数启用assert功能
        assert 2==instance.getpool().size();
    }
}

附录

github.com/maikec/patt… 个人github设计模式案例

声明

引用该文档请注明出处