1.定义
运用共享技术有效支持大量细粒度对象。
2.使用场景
1、系统有大量相似对象。 2、需要缓冲池的场景。
例如: 1、JAVA 中的 String,如果有则返回,如果没有则创建一个字符串保存在字符串缓存池里面。 2、数据库的连接池。
3.实现
/**
* 抽象享元(Flyweight)角色:是所有的具体享元类的基类,为具体享元规范需要实现的公共接口,非享元的外部状态以参数的形式通过方法传入。
* @author Administrator
*
*/
public interface Shape {
void draw();
}
/**
* 具体享元(Concrete Flyweight)角色:实现抽象享元角色中所规定的接口。
* @author Administrator
*
*/
public class CircleShape implements Shape{
private String color;
private int x;
private int y;
private int radius;
public CircleShape(String color) {
// TODO Auto-generated constructor stub
this.color = color;
}
public void setRadius(int radius) {
this.radius = radius;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("draw a circle[color="+color+",x="+x+",y="+y+",radius="+radius);
}
}
/**
* 享元工厂(Flyweight Factory)角色:负责创建和管理享元角色。当客户对象请求一个享元对象时,
* 享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。
* @author Administrator
*
*/
public class FlyWeightFactory {
private static HashMap<String,Shape> hashMap = new HashMap<>();
public static Shape getShape(String color) {
CircleShape shape = (CircleShape)hashMap.get(color);
if(shape==null) {
shape = new CircleShape(color);
hashMap.put(color, shape);
System.out.println("Creating circle of color : " + color);
}
return shape;
}
}
/**
* 测试类
* @author Administrator
*
*/
public class Test {
private final static String[] colors = new String[] {"red","green","yellow"};
public static void main(String[] args) {
for(int i=0;i<10;i++) {
CircleShape circle = (CircleShape)FlyWeightFactory.getShape(getRandomColor());
circle.setRadius(2);
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.draw();
}
}
private static String getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
private static int getRandomX() {
return (int)(Math.random()*100 );
}
private static int getRandomY() {
return (int)(Math.random()*100);
}
}
运行结果
4.总结
在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。
优点: 大大减少对象的创建,降低系统的内存,使效率提高。
缺点: 提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。