定义:
核心:
享元对象能做到共享的关建是区分了内部状态和外部状态。
内部状态:可以共享,不会随环境变化而变化
外部状态:不可以共享,会随环境变化而改变
例如我们要在森林中种树
package designmode.flyweight;
public class Tree {
private final String name;
private final String data;
public String getName() {
return name;
}
public String getData() {
return data;
}
public Tree(String name, String data) {
System.out.printf("%s创建成功",name);
this.name = name;
this.data = data;
}
}
package designmode.flyweight;
public class TreeNode {
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 Tree getTree() {
return tree;
}
public void setTree(Tree tree) {
this.tree = tree;
}
public TreeNode(int x, int y, Tree tree) {
super();
this.x = x;
this.y = y;
this.tree = tree;
}
private int x;
private int y;
private Tree tree;
}
package designmode.flyweight;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class TreeFactory {
private static Map<String,Tree> map = new ConcurrentHashMap<>();
public static Tree getTree(String name,String data) {
if(map.containsKey(name)) {
return map.get(name);
}
Tree tree = new Tree(name, data);
map.put(name, tree);
return tree;
}
}
package designmode.flyweight;
public class Client {
public static void main(String[] args) {
TreeNode node = new TreeNode(12,23,TreeFactory.getTree("松树", "30年的松树"));
TreeNode node1 = new TreeNode(2,12,TreeFactory.getTree("松树", "20年的树"));
}
}
享元模式实现:
FlyweightFactory享元工厂类:
创建并管理享元对象,享元池一般设计成键值对
FlyWeight抽象享元类:
通常是一个接口或抽象类,声明公共方法,这些方法可以向外界提供对象的内部状态,设置外部状态。
ConcreteFlyWeight具体享元类:
为内部状态提供成员变量进行存储
UnsharedConccreteFlyWeight非共享享元类:
不能被共享的子类可以设计为非共享享元类