设计模式-享元模式

享元模式分析

主要用于减少创建对象的数量,以减少内存占用和提高性能。尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。

代码示例

//享元模式
public class FlyweightModule {

    public interface Shape {
        void draw();
    }

    static 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);
        }
    }
}
class ShapeFactory {
    private static final HashMap<String, FlyweightModule.Shape> circleMap = new HashMap<String, FlyweightModule.Shape>();

    public static FlyweightModule.Shape getCircle(String color) {
        FlyweightModule.Circle circle = (FlyweightModule.Circle)circleMap.get(color);

        if(circle == null) {
            circle = new FlyweightModule.Circle(color);
            circleMap.put(color, circle);
            System.out.println("Creating circle of color : " + color);
        }
        return circle;
    }

    private static final String colors[] =
            { "Red", "Green", "Blue", "White", "Black" };
    public static void main(String[] args) {

        for(int i=0; i < 20; ++i) {
            FlyweightModule.Circle circle =
                    (FlyweightModule.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);
    }
}

优点:

  1. 大大减少对象的创建,降低系统的内存,使效率提高。

缺点:

  1. 提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章