黑马程序员技术交流社区

标题: 【上海校区】【设计模式】享元模式 [打印本页]

作者: 不二晨    时间: 2018-12-31 10:06
标题: 【上海校区】【设计模式】享元模式
模式定义

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


一个生动的例子

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



作者: 不二晨    时间: 2019-1-3 10:07
奈斯




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2