作用
- 运用共享技术有效地支持大量细粒度的对象。
何时使用
- 系统中有大量对象。
- 这些对象消耗大量内存。
- 这些对象的状态大部分可以外部化。
- 这些对象可以按照内蕴状态分为很多组,当把外蕴对象从对象中剔除出来时,每一组对象都可以用一个对象来代替。
- 系统不依赖于这些对象身份,这些对象是不可分辨的。
优点
- 大大减少对象的创建,降低系统的内存,使效率提高。
实例
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/3 14:08
* @Version:
* @Acton: 外部状态
*/
public class Coordinate {
private int x;
private int 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;
}
}
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/3 14:05
* @Version:
* @Acton: 享元类
*/
public interface ChessFlyweight {
void serColor(String color);
String getColor();
void display(Coordinate coordinate);
}
class ConcreateChess implements ChessFlyweight {
private String color;
public ConcreateChess(String color) {
this.color = color;
}
@Override
public void serColor(String color) {
this.color = color;
}
@Override
public String getColor() {
return color;
}
@Override
public void display(Coordinate coordinate) {
System.out.println("棋子的颜色:" + color);
System.out.println("棋子的位置:" + coordinate.getX()+ "__" + coordinate.getY());
}
}
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/3 14:31
* @Version:
* @Acton: 享元工厂类
*/
public class ChessFlyweightFactory {
//享元池
private static Map<String,ChessFlyweight> map = new HashMap<>();
public static ChessFlyweight getChess(String color){
if(map.get(color) != null){
return map.get(color);
}else {
ChessFlyweight cf = new ConcreateChess(color);
map.put(color,cf);
return cf;
}
}
}
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/3 11:38
* @Version:
* @Acton: 测试享元模式
*/
public class TestFlyWeightDemo {
public static void main(String[] args){
test1();
}
private static void test1() {
ChessFlyweight chess1 = ChessFlyweightFactory.getChess("黑色");
ChessFlyweight chess2 = ChessFlyweightFactory.getChess("黑色");
System.out.println(chess1);
System.out.println(chess2);
System.out.println("#====================增加外部状态的处理====================");
chess1.display(new Coordinate(10,10 ));
chess1.display(new Coordinate(20,20 ));
}
}