设计模式系列
1、组合模式
2、策略模式
3、单例模式
4、原型模式
5、模板模式
6、观察者模式
7、享元模式
8、装饰着模式
9、门面模式
10、责任链模式
11、建造者模式
12、适配器模式
什么是享元模式
使用共享技术,有效的减少创建对象的数量,减少JVM 内存的开销,减少内存占用提高性能,这种类型属于结构型模式。
码云地址:去看源码
示例
1、定义一个树对象
创建一个 Tree 类,作为原始对象,以游戏里面的树为例。
class Tree{
private final String name;
private final String color;
private final int high;
public Tree(String name, String color, int high) {
System.out.println("这里创建树");
this.name = name;
this.color = color;
this.high = high;
}
}
2、位置信息
定义一个类保存树的位置信息
class TreeNode{
private int x;
private int y;
private Tree tree;
public TreeNode(int x, int y, Tree tree) {
this.x = x;
this.y = y;
this.tree = tree;
}
}
3、创建树的工厂
定义一个工厂,来生成树的对象,需要一个 treeMap 来保存下之前已创建好的树对象,下一次用到这个对象,则不会再次创建,会从 map 中获取。
class TreeFactory{
private static Map<String,Tree> treeMap = new ConcurrentHashMap<>();
public static Tree getTree(String name, String color, int high){
if(treeMap.containsKey(name)){
return treeMap.get(name);
}
Tree tree = new Tree(name, color, high);
treeMap.put(name, tree);
return tree;
}
}
4、测试
public class FlyweightTest {
public static void main(String[] args) {
TreeNode treeNode = new TreeNode(1,2, TreeFactory.getTree("石头树", "green", 5));
TreeNode treeNode2 = new TreeNode(1,2, TreeFactory.getTree("石头树", "green", 5));
System.out.println(treeNode);
System.out.println(treeNode2);
}
}
运行结果:
这里创建树
com.example.pattern.flyweight.TreeNode@1b6d3586
com.example.pattern.flyweight.TreeNode@4554617c
会发现只创建了一次数对象。
5、总结
享元模式就是多个变量应用了同一个实例,这样节省了很多空间,节省了内存,避免浪费空间和性能;在 JDK 中的 String类,就是 final 的,就是一个享元模式;或者是数据库的连接池,多线程的线程池也都是享元模式的应用。
那么 享元模式 和 单例模式 是不是有点类似呢,都是最终获取到一个实例,那么单例和享元还是有本质的区别的,单例是类级别的,一个类只能实例化一个对象;享元是对象级别的,可以有多个对象实例,但是多个应用指向同一个实例。