享元模式就是 如果有很多个一样或者相似的对象;提高它的复用性;节省内存( 可能存在 时间换空间上的问题,这个避免不了);
核心:1. 共享的方式支持大量细粒度的复用;
2. 享元 做到共享的关键 一是 内部状态(共享的状态) 二是外部状态(不可共享的状态)
********************
实现结构:
1. 享元工厂类
2,抽象享元类
3,具体享元类
4,非共享享元类
********************
代码实现:
坐标类
package FlyWeight;
// 坐标类
public class Coordinate {
private int x,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;
}
public Coordinate(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
享元类
package FlyWeight;
/**
*
* 享元类接口
*
* */
public interface ChessFlyWeight {
void setColor(String c);
String getColor();
void display(Coordinate c);
}
/**
*
* 享元类
*
* */
class ConCreateChess implements ChessFlyWeight{
private String color;
public ConCreateChess(String color) {
super();
this.color = color; // 把颜色作为共享单元, 但是对于坐标作为不共享的单元
}
@Override
public void setColor(String c) {
// TODO Auto-generated method stub
this.color = c;
}
@Override
public String getColor() {
// TODO Auto-generated method stub
return color;
}
@Override
public void display(Coordinate c) {
// TODO Auto-generated method stub
System.out.println("棋子的颜色是:" + this.color);
System.out.println("棋子的坐标是x:"+c.getX()+"y:"+c.getY());
}
}
享元工厂
package FlyWeight;
import java.util.HashMap;
import java.util.Map;
/**
*
* 享元工厂类
*
* */
public class ChessFlyWeightFactory {
private static Map<String, ChessFlyWeight> map= new HashMap<String, ChessFlyWeight>();
public ChessFlyWeight getChessFlyWeight (String color) { // 把颜色作为共享单元, 但是对于坐标作为不共享的单元
if(map.get(color)==null) {
ChessFlyWeight cfw= new ConCreateChess(color);
map.put(color, cfw);
}
return map.get(color);
}
}
客户端
package FlyWeight;
public class Client {
public static void main(String[] args) {
ChessFlyWeight chess1 = new ChessFlyWeightFactory().getChessFlyWeight("black");
ChessFlyWeight chess2 = new ChessFlyWeightFactory().getChessFlyWeight("black");
System.out.println(chess1);
System.out.println(chess2);
System.out.println("外部状态处理=======");
chess1.display(new Coordinate(10, 20));
chess1.display(new Coordinate(20, 40));
}
}
来源:CSDN
作者:fire-fire-fox
链接:https://blog.csdn.net/wangrong111222/article/details/104111154