Skip to content

Commit fab9b5e

Browse files
author
Liu Yuning
committed
add flyweight DP
1 parent 29bb528 commit fab9b5e

3 files changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package designpattern.flyweight;
2+
3+
/**
4+
* 所有具体享元类的超类,接受并作用于外部状态
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public abstract class FlyWeight {
10+
11+
public abstract void operation(int extrinsicState);
12+
13+
}
14+
15+
class ConcreteFlyWeight extends FlyWeight {
16+
17+
@Override
18+
public void operation(int extrinsicState) {
19+
System.out.println("具体FlyWeight:" + extrinsicState);
20+
}
21+
22+
}
23+
24+
class UnsharedConcreteFlyWeight extends FlyWeight {
25+
26+
@Override
27+
public void operation(int extrinsicState) {
28+
System.out.println("不共享的具体FlyWeight:" + extrinsicState);
29+
}
30+
31+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package designpattern.flyweight;
2+
3+
/**
4+
* 客户端
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public class FlyWeightClient {
10+
public static void main(String[] args) {
11+
int extrinsicState = 22;
12+
13+
FlyWeightFactory f = new FlyWeightFactory();
14+
15+
FlyWeight fx = f.getFlyWeight("X");
16+
fx.operation(--extrinsicState);
17+
18+
FlyWeight fy = f.getFlyWeight("Y");
19+
fy.operation(--extrinsicState);
20+
21+
FlyWeight fz = f.getFlyWeight("Z");
22+
fz.operation(--extrinsicState);
23+
24+
FlyWeight uf = new UnsharedConcreteFlyWeight();
25+
uf.operation(--extrinsicState);
26+
27+
}
28+
29+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package designpattern.flyweight;
2+
3+
import java.util.HashMap;
4+
5+
/**
6+
* 享元工厂
7+
*
8+
* @author liu yuning
9+
*
10+
*/
11+
public class FlyWeightFactory {
12+
private HashMap<String, FlyWeight> flyWeights = new HashMap<String, FlyWeight>();
13+
14+
public FlyWeight getFlyWeight(String key) {
15+
if (!flyWeights.containsKey(key)) {
16+
flyWeights.put(key, new ConcreteFlyWeight());
17+
}
18+
19+
return flyWeights.get(key);
20+
}
21+
22+
}

0 commit comments

Comments
 (0)