享元模式

类图

代码

Flywight

1
2
3
4
5
6
abstract class Flyweight{

abstract String getColor();

abstract void display(Coordinate coordinate);
}

ConcreteFlyweight

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Chess extends Flyweight{

private String color;

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

@Override
String getColor() {
return this.color;
}

@Override
void display(Coordinate coordinate) {
System.out.println("棋子颜色:" + this.getColor());
System.out.println("棋子位置:" + coordinate);
}
}

UnsharedConcreteFlyweight

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
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;
}

@Override
public String toString() {
return "Coordinate{" +
"x=" + x +
", y=" + y +
'}';
}
}

FlywightFactory

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

private static Map<String, Chess> map = new HashMap<>();

public static Chess getChess(String color){
if(map.get(color) != null){
return map.get(color);
}

Chess chess = new Chess(color);
map.put(color, chess);
return chess;
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
public static void main(String args[]){

Chess chess1 = ChessFactory.getChess("黑");
Chess chess2 = ChessFactory.getChess("黑");

System.out.println(chess1);
System.out.println(chess2);

System.out.println("外部状态:");

chess1.display(new Coordinate(1, 1));
chess2.display(new Coordinate(2, 2));

}
}

运行结果

1
2
3
4
5
6
7
flyweight.Chess@4926097b
flyweight.Chess@4926097b
外部状态:
棋子颜色:黑
棋子位置:Coordinate{x=1, y=1}
棋子颜色:黑
棋子位置:Coordinate{x=2, y=2}

总结

概述

  1. 什么时候用享元模式

系统中有大量的对象,他们使系统的效率降低

这些对象的状态可以分离出所需要的内外两部分

数据库连接池就是标准的享元模式实现

优点

降低内存中对象的数量

缺点

享元模式分内蕴和外蕴(就是享元核心对象和不需要分享的对象),这两者之间划分不好的话,并不会减少对象数量,所以使用起来有一定局限性