美文网首页
Java设计模式--享元模式

Java设计模式--享元模式

作者: 留给时光吧 | 来源:发表于2018-04-18 20:32 被阅读0次

    享元模式主要是利用对对象的重复使用来减低内存的使用,主要思想是建立一个类似对象池的东西,对池内对象实现充分复用。简单实现:

    抽象接口

    public interface Shape {
        void draw();
    }
    

    具体实现

    public class Circle implements Shape{
        private String color;
        private int x,y,r;
    
        public Circle(String color){
            this.color = color;
        }
    
        public void setXYR(int x,int y,int r){
            this.x = x;
            this.y = y;
            this.r = r;
        }
    
        @Override
        public void draw() {
            System.out.println("draw circle: x = " + x + " , y = " + y + " , r = " + r + " , color = " + color);
        }
    }
    

    对象池管理类,对外提供对象

    public class ShapeFactory {
        private static final HashMap<String,Shape> map = new HashMap<>();
    
        public static Shape getCircle(String color){
            Circle circle = (Circle) map.get(color);
    
            if(circle == null){
                circle = new Circle(color);
                map.put(color,circle);
                System.out.println("create circle : " + color);
            }
    
            return circle;
        }
    }
    

    测试类

    public class test {
        private static final String colors[] =
                { "Red", "Green", "Blue"};
        public static void main(String[] args) {
            for(int i=0; i < 10; ++i) {
                Circle circle =
                        (Circle) ShapeFactory.getCircle(getRandomColor());
                circle.setXYR(getRandomX(),getRandomY(),10);
                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);
        }
    }
    

    结果:

    create circle : Red
    draw circle: x = 58 , y = 99 , r = 10 , color = Red
    create circle : Blue
    draw circle: x = 58 , y = 24 , r = 10 , color = Blue
    create circle : Green
    draw circle: x = 82 , y = 45 , r = 10 , color = Green
    draw circle: x = 99 , y = 61 , r = 10 , color = Green
    draw circle: x = 36 , y = 51 , r = 10 , color = Blue
    draw circle: x = 41 , y = 71 , r = 10 , color = Green
    draw circle: x = 2 , y = 3 , r = 10 , color = Green
    draw circle: x = 35 , y = 74 , r = 10 , color = Green
    draw circle: x = 25 , y = 74 , r = 10 , color = Green
    draw circle: x = 0 , y = 29 , r = 10 , color = Green
    

    可以发现,虽然我们调用了10次draw,每次circle对象的属性都不同,但是我们只实例化了3个对象,这样在打了频繁的调用某些类似对象时,能极大的减少资源消耗

    相关文章

      网友评论

          本文标题:Java设计模式--享元模式

          本文链接:https://www.haomeiwen.com/subject/ebubkftx.html