享元模式

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。

Diagram

Implementation

享元接口

1
2
3
public interface Flyweight  {
void doOperation(String extrinsicState);
}

享元实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ConcreteFlyweight implements Flyweight{

private String intrinsicState;

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

@Override
public void doOperation(String extrinsicState) {
System.out.println("Object address: " + System.identityHashCode(this));
System.out.println("IntrinsicState: " + intrinsicState);
System.out.println("ExtrinsicState: " + extrinsicState);
}
}

享元工厂类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class FlyweightFactory {

private HashMap<String,Flyweight> flyweightHashMap = new HashMap<>();


Flyweight getFlyweight(String intrinsicState){
if(!flyweightHashMap.containsKey(intrinsicState)){
Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
flyweightHashMap.put(intrinsicState,flyweight);
}
return flyweightHashMap.get(intrinsicState);
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
public class FlyweightTest {

@Test
public void test() {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight1 = factory.getFlyweight("aa");
Flyweight flyweight2 = factory.getFlyweight("aa");
flyweight1.doOperation("x");
flyweight2.doOperation("y");
}
}

Example

Java 利用缓存来加速大量小对象的访问时间。

  • java.lang.Integer#valueOf(int)
  • java.lang.Boolean#valueOf(boolean)
  • java.lang.Byte#valueOf(byte)
  • java.lang.Character#valueOf(char)

Reflence