当前位置: 移动技术网 > IT编程>开发语言>Java > 设计模式——共享模式

设计模式——共享模式

2019年05月18日  | 移动技术网IT编程  | 我要评论

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

/**
 * 需要被共享的对象
 * @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设计模式案例

声明

引用该文档请注明出处

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网