设计模式之:享元模式
作者:互联网
业务场景
(1)我们现在要缓存一些数据,比如说权限,根据权限的ID作为key,权限数据自己本身是value
(2)但是我们不需要使用太复杂的ehcache框架之类的去使用,特别特别的简单的
(3)我们就想基于自己的Map去实现一套东西
享元模式,从最基本的角度来说,其实就是维护固定数量的对象实例,不同的对象实例,只有一个,然后保存在内部的一个map中。可以算是跟单例模式的一个扩展和结合吧。
import java.util.HashMap;
import java.util.Map;
public class FlyweightPatternDemo {
public static void main(String[] args) {
Flyweight flyweight1 = FlyweightFactory.get("对象1");
flyweight1.execute();
Flyweight flyweight2 = FlyweightFactory.get("对象1");
flyweight2.execute();
System.out.println(flyweight1 == flyweight2);
/**
* 享元
* 享受,元数据
* 同一个数据,我就认为是一个元数据,整个系统里这个数据就一份,缓存起来
* 整个系统对这个数据,全部享受他一个对象实例即可
* 直接既有内存来缓存一块数据,用享元模式
*/
}
public static interface Flyweight {
void execute();
String getName();
void setName(String name);
}
public static class ConcreteFlyweight implements Flyweight {
private String name;
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
public ConcreteFlyweight(String name) {
super();
this.name = name;
}
@Override
public void execute() {
System.out.println(name + "执行功能逻辑");
}
}
public static class FlyweightFactory {
private static Map<String, Flyweight> cachePool = new HashMap<>();
public static Flyweight get(String name) {
Flyweight flyweight = cachePool.get(name);
if (flyweight == null) {
flyweight = new ConcreteFlyweight(name);
cachePool.put(name, flyweight);
}
return flyweight;
}
}
}
标签:享元,String,void,模式,static,Flyweight,设计模式,public,name 来源: https://blog.csdn.net/qq_33746789/article/details/97942609