享元模式就是单例模式的扩展,目的同样是避免重复创建对象,不过享元模式并不像单例模式一样,一个类只创建一个单例,享元模式避免重复创建的对象是指相同的 class 可能他们的内部属性是相同的,如果当某个属性相同的时候就不重复创建对象,而是重用该对象。

比如说我们需要创建多种不同颜色的圆圈,我们先创建一个蓝色的圆圈,一个红色的圆圈,当以后再需要蓝色和红色的圆圈的时候,我们就重用这两个对象。

下面是代码实现

先定义一个形状接口

1
2
3
public interface Shape {
    void draw();
}

然后给出形状的实现,并且内部带一个颜色属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Circle implements Shape {
    private String color;

    public Circle(String color) {
        this.color = color;
    }

    @Override
    public void draw() {
        System.out.println(String.format("[%s] circle, class hash: [%s]", color, this.hashCode()));
    }
}

然后我们通过一个工厂来创建该实例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;
    }
}

最后我们通过测试类看看效果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Main {
    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.draw();
        }
    }
    private static String getRandomColor() {
        return colors[(int)(Math.random()*colors.length)];
    }
}

打印出的结果显示出每种颜色只创建了一次,如下是打印结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Creating circle of color : Blue
[Blue] circle, class hash: [607635164]
[Blue] circle, class hash: [607635164]
[Blue] circle, class hash: [607635164]
Creating circle of color : Red
[Red] circle, class hash: [110456297]
Creating circle of color : White
[White] circle, class hash: [1989972246]
Creating circle of color : Black
[Black] circle, class hash: [1791930789]
[White] circle, class hash: [1989972246]
[Blue] circle, class hash: [607635164]
Creating circle of color : Green
[Green] circle, class hash: [762152757]
[Red] circle, class hash: [110456297]
[Green] circle, class hash: [762152757]
[Green] circle, class hash: [762152757]
[White] circle, class hash: [1989972246]
[Black] circle, class hash: [1791930789]
[Blue] circle, class hash: [607635164]
[Red] circle, class hash: [110456297]
[Green] circle, class hash: [762152757]
[Black] circle, class hash: [1791930789]
[Green] circle, class hash: [762152757]
[Black] circle, class hash: [1791930789]

参考资料

  1. 菜鸟教程:享元模式