享元模式

“有则取出返回,没有则创建添加并返回。”

构造接口和类

首先创建水果接口:

1
2
3
interface FruitFlyweight {
void printColor();
}

然后创建水果类:

1
2
3
4
5
6
7
8
9
10
11
12
13
class OrangeFlyweight implements FruitFlyweight {
private String color;
public OrangeFlyweight(String color) {
this.color = color;
}
@Override
public void printColor() {
System.out.println(color + " " + this);
}
}

最后这行打印this的目的是为了在输出时,显示对象的HashCode,进而判断打印的是哪一个对象;

构造工厂

构造工厂的过程,揭示了享元模式的基本原理,首先,当我们需要在一个map中取一个value的时候,判断它是否为空,如果不为空,那么就返回,如果为空,那么就创建相应的对象,添加到map中,并返回,在某些场景能很好的节约开销。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
class FruitFactoryFlayweight {
private static final Map<String, FruitFlyweight> fruitMap = new HashMap<>();
public static FruitFlyweight getFruitflyweight(String color) {
FruitFlyweight flyweight = fruitMap.get(color);
if (flyweight == null) {
flyweight = new OrangeFlyweight(color);
fruitMap.put(color, flyweight);
}
return flyweight;
}
}

测试用例

1
2
3
4
5
6
public class FlyweightDemo {
public static void main(String[] args) {
FruitFactoryFlayweight.getFruitflyweight("Red").printColor();
FruitFactoryFlayweight.getFruitflyweight("Red").printColor();
}
}

输出为:

1
2
3
4
Red com.cg.OrangeFlyweight@3cd1a2f1
Red com.cg.OrangeFlyweight@3cd1a2f1
Process finished with exit code 0

原本的map为空,调用getFruitflyweight方法后,会创建水果对象,当再次调用getFruitflyweight时,会反回之前存在的对象。