享元模式(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()); } }