一. 前言:
享元模式(思想是有趣的),在23中设计模式之中偏向于结构型。运用共享技术来有效地支持大量细粒度对象的复用。它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
二. 过程:
-
图解:
-
享元模式
/** * 享元模式 * 类似于池化思想 (可共享元数据),比如:连接池 * 其实在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。 * 用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象。 * @author chengxi * @date 2020/8/25 13:50 */ public class Flower { String id = UUID.randomUUID().toString(); /** * 这里以花为例,是否凋谢代表其本身能否使用的标志 * 在花海中,构成共享 */ Boolean isWither = false; @Override public String toString() { return "Flower{" + "id='" + id + '\'' + ", isWither=" + isWither + '}'; } } class FlowPool{ static Map<String, Flower> flowerMap = new HashMap<>(); static { for (int i = 0; i < 10; i++) { createFlower(); } } public Flower getFlower(String id){ if (StringUtils.isEmpty(id) || flowerMap.get(id) == null) { Flower flower = createFlower(); return flower; } return new Flower(); } public static Flower createFlower() { Flower flower = new Flower(); flowerMap.put(flower.id, flower); return flower; } } class TestMain{ public static void main(String[] args) { FlowPool flowPool = new FlowPool(); for (int i = 0; i < 10; i++) { System.out.println(flowPool.getFlower(null)); } } }
三. 后语
有时候在对象存在高度重复性的时候,为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性。如何抉择,就看个人把控了。