码迷,mamicode.com
首页 > 其他好文 > 详细

享元模式

时间:2017-10-24 20:44:37      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:import   oid   提高   nta   cli   flyweight   log   else   class   

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。

享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象

 

 Flywieght

package design.pattern.flyweight;

public class Flyweight {
    private String msg;
    public Flyweight(String msg) {
        this.msg = msg;
    }
    public String getMsg() {
        return msg;
    }
}

FlyweightFactory

package design.pattern.flyweight;

import java.util.HashMap;
import java.util.Map;

public class FlyweightFactory {
    private Map<String, Flyweight> pool = new HashMap<>();
    public Flyweight getFlyweight(String key) {
        if (pool.containsKey(key)) {
            return pool.get(key);
        } else {
            Flyweight obj = new Flyweight(key);
            pool.put(key, obj);
            
            return obj;
        }
    }
}

Client

package design.pattern.flyweight;

public class Client {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        System.out.println(factory.getFlyweight("hello world").getMsg());
    }
}

 

享元模式

标签:import   oid   提高   nta   cli   flyweight   log   else   class   

原文地址:http://www.cnblogs.com/m2492565210/p/7461581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!