享元模式

模式的定义

运用共享技术有效地支持大量细粒度的对象.

代码演示

享元接口

1
2
3
4
5
6
7
8
9
10
11

* 功能描述: 享元模式
* 享元接口
*
* @author sunzhiqiang
* @create 2018-08-15
*/
public interface {

void opration(String extrinsicState);
}

具体享元对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

* 功能描述: 享元模式
* 具体享元
*
* @author sunzhiqiang
* @create 2018-08-15
*/
class ConcreteFlyWeight implements {

private String intrinsicState;

public ConcreteFlyWeight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}


public void opration(String extrinsicState) {

System.out.println(intrinsicState + extrinsicState);
}
}

享元工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

* 功能描述: 享元模式
* 享元工厂
*
* @author sunzhiqiang
* @create 2018-08-15
*/
public final class FlyWeightFactory {

private static final FlyWeightFactory FACTORY = new FlyWeightFactory();

private final ConcurrentHashMap<String,SoftReference<FlyWeight>> cache = new ConcurrentHashMap<>();

private FlyWeightFactory() {

}

public static FlyWeightFactory factory() {
return FACTORY;
}

public FlyWeight getFlyWeight(String key){

if(cache.get(key) != null){
return cache.get(key).get();

}else{
FlyWeight flyWeight = new ConcreteFlyWeight(key);
cache.putIfAbsent(key,new SoftReference<>(flyWeight));
return flyWeight;
}
}
}