GOF23设计模式(九)

GOF设计模式之享元模式(FlyWeight)

享元模式以共享的方式高效地支持大量细粒度对象的重用。
享元对象能做到共享的关键是区分了内部状态和外部状态
·内部状态:可以共享,不会随环境变化而改变
·外部状态:不可以共享,会随环境变化而改变

享元类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 享元类
*/
public interface ChessFlyWeight {
void setColor(String c);
String getColor();
void display(Coordinate c);
}

class ConcreteChess implements ChessFlyWeight{
private String color;

public ConcreteChess(String color) {
this.color = color;
}

@Override
public void setColor(String c) {
this.color=c;
}

@Override
public String getColor() {
return color;
}

@Override
public void display(Coordinate c) {
System.out.println("棋子颜色"+color);
System.out.println("棋子位置"+c.getX()+"-----"+c.getY());
}
}

外部状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 外部状态UnSharedConcreteFlayWeight
*/
public class Coordinate {
private int x,y;

public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}
}

享元工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 享元工厂
*
*/
public class ChessFlyWeightFactory {
//享元池
private static Map<String,ChessFlyWeight> map=new HashMap<String,ChessFlyWeight>();

public static ChessFlyWeight getChess(String color) {
if(map.get(color)!=null) {
return map.get(color);
}else {
ChessFlyWeight cfw=new ConcreteChess(color);
map.put(color,cfw);
return cfw;
}
}
}

测试

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

public static void main(String[] args) {
ChessFlyWeight chess1=ChessFlyWeightFactory.getChess("黑色");
ChessFlyWeight chess2=ChessFlyWeightFactory.getChess("黑色");
System.out.println(chess1);
System.out.println(chess2);
System.out.println("外部状态处理");
chess1.display(new Coordinate(12,5));
chess2.display(new Coordinate(15,7));
}
}

结果

FlyWeight.ConcreteChess@15db9742
FlyWeight.ConcreteChess@15db9742
外部状态处理
棋子颜色黑色
棋子位置12—–5
棋子颜色黑色
棋子位置15—–7

原创技术分享,您的支持将鼓励我继续创作
0%