享元模式
享元模式概念
享元模式(Flyweight Pattern):运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于 享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,它是一种 对象结构型模式。
享元模式类图
这里盗了个别人的图
享元模式代码示例
-
享元接口
package com.xfc.design.patterns.flyweight; /** * 享元接口 * * @author xf * @date 2019/12/23 15:32 */ public interface FlyWeight { /** * 享元模式中的方法 * @param state * @return */ Object execute(String state); }
-
享元接口具体实现
package com.xfc.design.patterns.flyweight; /** * 具体享元类,实现享元接口。该类的对象将被复用 * * @author xf * @date 2019/12/23 15:34 */ public class ConcreteFlyWeight implements FlyWeight { /** * 实例名称 */ private String name; public ConcreteFlyWeight(String name) { this.name = name; } /** * 享元模式中的方法 * * @param externalState 外部状态 * @return */ @Override public Object execute(String externalState) { return this.name + " -> " + externalState + " -> " + this.hashCode(); } }
-
享元工厂
package com.xfc.design.patterns.flyweight; import java.util.HashMap; import java.util.Map; /** * 享元工厂 * * @author xf * @date 2019/12/23 15:40 */ public class FlyWeightFactory { /** * 享元池 */ private final static Map<String,FlyWeight> flyWeightFactories = new HashMap<>(); /** * 根据名称获取享元类 * @param name * @return */ public static FlyWeight getInstance(String name){ // double check for thread security if(flyWeightFactories.get(name) == null){ synchronized (flyWeightFactories){ if(flyWeightFactories.get(name) == null) { flyWeightFactories.put(name, new ConcreteFlyWeight(name)); } } } return flyWeightFactories.get(name); } }
-
测试
package com.xfc.design.patterns.flyweight; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * 享元模式测试 * 相同的状态下不同新产生实例对象,这就是享元模式的重要作用,解决了实例过多导致的性能下降问题 * 并且可以通过外部状态改变相同实例的行为 */ class FlyWeightTest { @Test void execute() { FlyWeight instance = FlyWeightFactory.getInstance("A"); final Object resultA = instance.execute("A-state"); FlyWeight instanceB = FlyWeightFactory.getInstance("B"); final Object resultB = instanceB.execute("B-state"); FlyWeight instanceA1 = FlyWeightFactory.getInstance("A"); final Object resultA1 = instanceA1.execute("A-state-1"); FlyWeight instanceB1 = FlyWeightFactory.getInstance("B"); final Object resultB1 = instance.execute("B-state-1"); System.out.println("resultA = " + resultA); System.out.println("resultB = " + resultB); System.out.println("resultA-1 = " + resultA1); System.out.println("resultB-1 = " + resultB1); // 相同的状态下不同新产生实例对象,这就是享元模式的重要作用,解决了实例过多导致的性能下降问题 Assertions.assertAll("instances", () -> Assertions.assertEquals(instance, instanceA1), () -> Assertions.assertEquals(instanceB, instanceB1)); } }
技术交流 jannik.xf2016@gmail.com