享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式,享元模式是池技术的重要实现方式。
场景
- 系统中存在大量的相似对象
- 细粒度的对象都具有相似的外部状态,而且内部状态与环境无关,也就是说对象没有特定身份
- 需要缓冲池的场景
实现
源码来自: 菜鸟教程-设计模式
创建抽象接口以及实体类
Shape.java
public interface Shape {
void draw();
}
Circle.java
public class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
public Circle(String color){
this.color = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle: Draw() [Color : " + color
+", x : " + x +", y :" + y +", radius :" + radius);
}
}
创建一个工厂,生成基于给定信息的实体类的对象,重用对象
public class ShapeFactory {
private static final HashMap<String, Shape> circleMap = new HashMap<>();
public static Shape getCircle(String color) {
Circle circle = (Circle)circleMap.get(color);
if(circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating circle of color : " + color);
}
return circle;
}
}
使用示例
public class FlyweightPatternDemo {
private static final String colors[] =
{ "Red", "Green", "Blue", "White", "Black" };
public static void main(String[] args) {
for(int i=0; i < 20; ++i) {
Circle circle =
(Circle)ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
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);
}
}
在这个例子中,Color 作为内部状态是不变的,其他属性作为可变的外部状态。
优点
- 减少应用程序创建的对象,降低程序内存占用,增强程序性能
缺点
- 使系统变得复杂,为了共享内存,需要将一些状态外部化
- 外部化状态固有固化特性,不应该随着内部系统的变化为改变,否则会导致系统的逻辑混乱
Android 中的应用
- Message对象的创建,
Message.obtain()
参考
书籍:《设计模式之禅》、《Android源码设计模式》
技术文章:菜鸟教程-设计模式