在Microsoft Visio中点击一个图像,会在这个图像边缘出现一个方形的框,现在来实现这个框。
写之前强烈推荐一下别人写的博客,简单明了
当我们想要对一个类或多个类的功能进行扩充,通常就在这个类或父类中做改变,装饰着模式,就是在不改变原有类的功能属性的情况下,对这个类进行动态的扩展,而这个类什么也不用管,只需用自己做自己的就好了。
装饰着模式,很重要的一点就是,装饰者类与被装饰者类要实现共同的接口。装饰者类,面向的不是对类,而是接口,通过对接口的操作,来实现对类的扩展。
被装饰的类的接口
public interface DataInterface { public void addChild(DataInterface baseData); public void removeChild(int index); public void move(float moveX ,float moveY); public void draw(Canvas canvas); public ListgetChild(); public DataType[] pointIsInside(float moveX , float moveY); public void writer(BufferedWriter bufferedWriter); public DataInterface read(BufferedReader bufferedReader); public float[] getMaxMinXY(boolean checkOrRadio);}
这个接口中,与我上一篇博客,最大的不同,是,传入的参数不再是一个父类,而是一个接口,凡是实现这个接口的类都能传入
装饰者类的接口
public interface DecorationModeInterface extends DataInterface {}
装饰者类有自己扩展这个类的接口:
private boolean aBoolean ;private float[] floats;private DataInterface dataInterface;public DecorationMode(DataInterface dataInterface){ this.dataInterface = dataInterface;}@Overridepublic void addChild(DataInterface baseData) { this.dataInterface.addChild(baseData);}@Overridepublic void removeChild(int index) { this.dataInterface.removeChild(index);}@Overridepublic void move(float moveX, float moveY) { this.dataInterface.move(moveX , moveY);}@Overridepublic void draw(Canvas canvas) { this.dataInterface.draw(canvas); if (isaBoolean()) { drawRectangle(getFloats(), canvas); setaBoolean(false); }}@Overridepublic ListgetChild() { return this.dataInterface.getChild();}@Overridepublic DataType[] pointIsInside(float moveX, float moveY) { return this.dataInterface.pointIsInside(moveX,moveY);}@Overridepublic void writer(BufferedWriter bufferedWriter) { this.dataInterface.writer(bufferedWriter);}@Overridepublic DataInterface read(BufferedReader bufferedReader) { return this.dataInterface.read(bufferedReader);}@Overridepublic float[] getMaxMinXY(boolean checkOrRadio) { float[] floats = this.dataInterface.getMaxMinXY(checkOrRadio); float[] floats1 = {floats[0] - 10 ,floats[1] - 10 ,floats[2] + 10,floats[3] + 10}; setFloats(floats1); setaBoolean(checkOrRadio); return getFloats();}public boolean isaBoolean() { return aBoolean;}public void setaBoolean(boolean aBoolean) { this.aBoolean = aBoolean;}public float[] getFloats() { return floats;}public void setFloats(float[] floats) { this.floats = floats;}//float left, float top, float right, float bottomprivate RectangleData rectangleData = new RectangleData();void drawRectangle(float[] floats ,Canvas canvas){ rectangleData.setRectF(new RectF(floats[0] , floats[1],floats[2],floats[3])); rectangleData.setPaintAlpha(100); rectangleData.setPaintStyle(Paint.Style.STROKE); rectangleData.setPaintColor(Color.RED); rectangleData.setWight(10); rectangleData.draw(canvas);}
drawRectangle:为需要画框出来的类,画出来。
装饰者类,其实就是在 所有需要被装饰的类的外面,嵌套一层 装饰者类,用装饰着类去包裹住被装饰者,调用装饰者,在装饰着中执行扩展的方法,然后执行原有的方法。实现对类的扩展