运用享元模式(Flyweight)可以有效地支持大量细粒度的对象。
类结构
代码
1package com.elltor.designpattern.Flyweight;
2
3public interface Flyweight {
4 void operation(int i);
5}
1package com.elltor.designpattern.Flyweight;
2
3public class ConcreteFlyweight implements Flyweight {
4
5 @Override
6 public void operation(int i) {
7 System.out.println("具体的享元对象: "+i);
8 }
9}
1package com.elltor.designpattern.Flyweight;
2
3import java.util.HashMap;
4
5public class FlyweightFcatory {
6 private HashMap<String,ConcreteFlyweight> flyweightMap = new HashMap<>();
7
8 public FlyweightFcatory() {
9 flyweightMap.put("A",new ConcreteFlyweight());
10 flyweightMap.put("B",new ConcreteFlyweight());
11 flyweightMap.put("C",new ConcreteFlyweight());
12 flyweightMap.put("D",new ConcreteFlyweight());
13 flyweightMap.put("E",new ConcreteFlyweight());
14 }
15
16 public Flyweight getFlyweight(String key){
17 return flyweightMap.get(key);
18 }
19}
1package com.elltor.designpattern.Flyweight;
2
3public class UnsharedFlyweight implements Flyweight {
4 @Override
5 public void operation(int i) {
6 System.out.println("不被共享的享元对象: "+i);
7 }
8}
1package com.elltor.designpattern.Flyweight;
2
3public class Main {
4 public static void main(String[] args) {
5 int i = 100;
6 FlyweightFcatory factory = new FlyweightFcatory();
7
8 Flyweight flyweightA = factory.getFlyweight("A");
9 flyweightA.operation(i);
10
11 Flyweight flyweightB = factory.getFlyweight("B");
12 flyweightB.operation(i*2);
13
14 Flyweight flyweightC = factory.getFlyweight("C");
15 flyweightC.operation(i*3);
16
17 Flyweight flyweightD = factory.getFlyweight("D");
18 flyweightD.operation(i*4);
19
20 Flyweight flyweightE = factory.getFlyweight("E");
21 flyweightE.operation(i*5);
22 }
23
24}
25//打印结果
26具体的享元对象: 100
27具体的享元对象: 200
28具体的享元对象: 300
29具体的享元对象: 400
30具体的享元对象: 500
抽离表象, 用同一个对象表示不同"外观"的对象, 这些"外观"的差异是由数据的不同而产生。