23种设计模式:享元模式
享元模式
1.介绍
概念
享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。
享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。我们将通过创建 5 个对象来画出 20 个分布于不同位置的圆来演示这种模式。由于只有 5 种可用的颜色,所以 color 属性被用来检查现有的 Circle 对象。
主要作用
运用共享技术有效地支持大量细粒度的对象。
解决的问题
在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。
使用场景
1、系统有大量相似对象。 2、需要缓冲池的场景。
(引用自菜鸟教程)
2.实现
背景
实现一个计算器。
实现步骤
1.创建一个Shape接口
public interface Shape {
void draw();
}
2.创建Rectangle类。
public class Rectangle implements Shape{
private String color;
private int length;
private int width;
public Rectangle(String color) {
this.color = color;
}
public void setLength(int length) {
this.length = length;
}
public void setWidth(int width) {
this.width = width;
}
@Override
public void draw() {
System.out.println("Draw rectangle:");
System.out.println("color: " + color);
System.out.println("length: " + length);
System.out.println("width: " + width);
}
}
3.创建一个ShapeFactory类。
public class ShapeFactory {
protected static final HashMap<String, Rectangle> rectangleMap = new HashMap<>();
public static Shape getRectangle(String color) {
Rectangle rectangle = (Rectangle) rectangleMap.get(color);
if (rectangle == null) {
rectangle = new Rectangle(color);
rectangleMap.put(color, rectangle);
System.out.println("Creating rectangle of color: " + color);
}
return rectangle;
}
}
4.创建测试类
public class FlyweightPatternDemo {
public static void main(String[] args) {
Shape rectangle1 = new Rectangle("red");
Shape rectangle2 = new Rectangle("blue");
Shape rectangle3 = new Rectangle("yellow");
ShapeFactory.rectangleMap.put("red", (Rectangle) rectangle1);
ShapeFactory.rectangleMap.put("blue", (Rectangle) rectangle2);
ShapeFactory.rectangleMap.put("yellow", (Rectangle) rectangle3);
Shape rectangle4 = ShapeFactory.getRectangle("red");
Shape rectangle5 = ShapeFactory.getRectangle("pink");
rectangle4.draw();
rectangle5.draw();
}
}
5.运行结果
Creating rectangle of color: pink
Draw rectangle:
color: red
length: 0
width: 0
Draw rectangle:
color: pink
length: 0
width: 0