Skip to content

Commit

Permalink
add flyweight DP
Browse files Browse the repository at this point in the history
  • Loading branch information
Liu Yuning committed May 21, 2017
1 parent 29bb528 commit fab9b5e
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/designpattern/flyweight/FlyWeight.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package designpattern.flyweight;

/**
* 所有具体享元类的超类,接受并作用于外部状态
*
* @author liu yuning
*
*/
public abstract class FlyWeight {

public abstract void operation(int extrinsicState);

}

class ConcreteFlyWeight extends FlyWeight {

@Override
public void operation(int extrinsicState) {
System.out.println("具体FlyWeight:" + extrinsicState);
}

}

class UnsharedConcreteFlyWeight extends FlyWeight {

@Override
public void operation(int extrinsicState) {
System.out.println("不共享的具体FlyWeight:" + extrinsicState);
}

}
29 changes: 29 additions & 0 deletions src/designpattern/flyweight/FlyWeightClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package designpattern.flyweight;

/**
* 客户端
*
* @author liu yuning
*
*/
public class FlyWeightClient {
public static void main(String[] args) {
int extrinsicState = 22;

FlyWeightFactory f = new FlyWeightFactory();

FlyWeight fx = f.getFlyWeight("X");
fx.operation(--extrinsicState);

FlyWeight fy = f.getFlyWeight("Y");
fy.operation(--extrinsicState);

FlyWeight fz = f.getFlyWeight("Z");
fz.operation(--extrinsicState);

FlyWeight uf = new UnsharedConcreteFlyWeight();
uf.operation(--extrinsicState);

}

}
22 changes: 22 additions & 0 deletions src/designpattern/flyweight/FlyWeightFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package designpattern.flyweight;

import java.util.HashMap;

/**
* 享元工厂
*
* @author liu yuning
*
*/
public class FlyWeightFactory {
private HashMap<String, FlyWeight> flyWeights = new HashMap<String, FlyWeight>();

public FlyWeight getFlyWeight(String key) {
if (!flyWeights.containsKey(key)) {
flyWeights.put(key, new ConcreteFlyWeight());
}

return flyWeights.get(key);
}

}

0 comments on commit fab9b5e

Please sign in to comment.