java设计模式参考文章:
Java设计模式实战,23种设计模式介绍以及在Java中的实现,Java设计模式, Java经典设计模式之五大创建型模式
## 定义 ##
运用共享技术有效地支持大量细粒度的对象。
## 代码示例 ##
- 一盘棋的棋子大小、材质、颜色(黑/白)往往都是确定的,而围棋落子的位置却不一定, 因此我们可以将棋子位置从棋子对象中剥离,然后让棋子对象共享大小、材质、颜色属性, 并在调用时将位置传入, 就可大大减少子对象的所占据的内存空间。
/**
* @author bwx
* @date 2017/11/28
* 享元模式抽象接口
*/
public interface Flyweight {
void operation(Location location);
}
/**
* @author bwx
* @date 2017/11/28
* 棋子的位置
*/
public class Location {
private int locX;
private int locY;
public int getLocX() {
return locX;
}
public void setLocX(int locX) {
this.locX = locX;
}
public int getLocY() {
return locY;
}
public void setLocY(int locY) {
this.locY = locY;
}
@Override
public String toString() {
return "Location{" +
"locX=" + locX +
", locY=" + locY +
'}';
}
}
public class WeiqiFlyweight implements Flyweight {
private String color;
private double radius;
private String material;
public WeiqiFlyweight(String color, double radius, String material) {
this.color = color;
this.radius = radius;
this.material = material;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
public void operation(Location location) {
System.out.println("[" + color + "]棋 [" + material + "]材质 半径[" + radius + "]CM 落在" + location);
}
}
public class FlyweightFactory {
private static Map<String, WeiqiFlyweight> map = new ConcurrentHashMap<String, WeiqiFlyweight>();
public static WeiqiFlyweight getWeiqiFlyweight(String color) {
WeiqiFlyweight flyweight = map.get(color);
if (flyweight == null) {
flyweight = new WeiqiFlyweight(color, 1.1, "陶瓷");
map.put(color, flyweight);
}
return flyweight;
}
public static int size() {
return map.size();
}
}
public class Main {
public static void main(String[] args) {
FlyweightFactory.getWeiqiFlyweight("black");
FlyweightFactory.getWeiqiFlyweight("white");
FlyweightFactory.getWeiqiFlyweight("black");
FlyweightFactory.getWeiqiFlyweight("white");
System.out.println(FlyweightFactory.size());
}
}
## 优点 ##
享元模式可以极大减少内存中对象的数量: 相同/相似对象只保留一份, 节约资源, 提高性能. 且将外部状态剥离, 使外部状态相对独立, 不影响内部状态. 但相比原先的设计, 增加了实现复杂度, 且读取外部状态使得运行时间变长(时间换空间).
缺点
享元模式使得系统更加复杂。
- 为了使对象可以共享,需要将一些状态外部化,这使得程序的逻辑复杂化。
享元模式将享元对象的状态外部化,而读取外部状态使得运行时间变长。
解析