设计模式:享元模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SpeedMe/article/details/41900803

原文地址:http://leihuang.org/2014/12/09/flyweight/


Structural 模式 如何设计物件之间的静态结构,如何完成物件之间的继承、实 现与依赖关系,这关乎着系统设计出来是否健壮(robust):像是易懂、易维护、易修改、耦合度低等等议题。Structural 模式正如其名,其分类下的模式给出了在不同场合下所适用的各种物件关系结构。


享元模式用于降低对象的创建数量,提升程序性能.java中String就是利用了享元模式,就是如果对象内容相同时就不创建新的对象,如果不存在与之相同内容的对象时,才创建一个新的对象.

String str1 = "abc" ;
String str2 = "abc" ;
System.out.println(str1==str2) ;

上面这段代码输出true,因为String就是利用了享元模式.

下面我们来实现一个享元模式,一个形状接口Shape,长方形Rectangle实现Shape接口,我们让客户端创造不同颜色的长方形,相同颜色的记为内容相同.类结构图如下:

img

Shape 接口

public interface Shape {
    public void draw() ;
}

Rectangle 类

public class Rectangle implements Shape {

    private int width, height;
    private String color;

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

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }


    @Override
    public void draw() {
        System.out.println("width:" + width + "  height:" + height + "  color:"
                + color);
    }
}

ShapeFactory 类

扫描二维码关注公众号,回复: 3856268 查看本文章
public class ShapeFactory {
    private static HashMap<String,Shape> hs = new HashMap<String,Shape>() ;

    public static Shape getShape(String color){
        Shape shape = hs.get(color);

        if(shape==null){
            shape = new Rectangle(color) ;
            hs.put(color, shape) ;
        }
        return shape;
    }

    public static int size(){
        return hs.size() ;
    }
}

Client 类

public class Client {
    private static String[] colors = { "red", "blue", "yellow", "green",
            "black" };

    public static void main(String[] args) {
        Rectangle rectangle = null ;
        for (int i=0;i<20;i++) {
            rectangle = (Rectangle) ShapeFactory.getShape(getRandomColor());
            rectangle.setHeight(i);
            rectangle.setWidth(i);

            rectangle.draw();
        }
        System.out.println(ShapeFactory.size()) ; //always 5
    }

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


猜你喜欢

转载自blog.csdn.net/SpeedMe/article/details/41900803
今日推荐