A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

模式定义

享元模式主要用于减少创建对象的数量,以减少内存占用和提高性能。


一个生动的例子

Flyweight抽象类:
public interface Shape {
        void draw();
}

Flyweight具体类:
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);
        }
}
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
26
27
28
29
30
31
32
33
FlyweightFactory类:
public class ShapeFactory {
        private static final Map<String, Circle> CIRCLE_MAP = new HashMap<>();

        public static Circle getCircle(String color) {
                Circle circle = CIRCLE_MAP.get(color);
                if (circle == null) {
                        circle = new Circle(color);
                        CIRCLE_MAP.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
客户端:
public class FlyweightTest {
        private static final String CORLORS[] = { "Red", "Green", "Blue", "White", "Black" };
        private static int length = CORLORS.length;

        public static void main(String[] args) {
                for (int i = 0; i < 20; i++) {
                        Circle circle = ShapeFactory.getCircle(getRandomColor());
                        circle.setX(getRandomX());
                        circle.setY(getRandomY());
                        circle.setRadius(100);
                        circle.draw();
                }
        }

        private static String getRandomColor() {
                return CORLORS[(int) (Math.random() * length)];
        }

        private static int getRandomX() {
                return (int) (Math.random() * 100);
        }

        private static int getRandomY() {
                return (int) (Math.random() * 100);
        }
}
---------------------
转载,仅作分享,侵删
作者:EagleLi1
原文:https://blog.csdn.net/qq_21687635/article/details/85095149


1 个回复

倒序浏览
奈斯
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马