常用设计模式总结--代理模式

来源:互联网 发布:ubuntu查看目录 编辑:程序博客网 时间:2024/05/16 06:56

代理模式就不废话了,这个模式在生活中很常见,打官司、租房子的都需要找个专业的人来替你处理不擅长的事。

鉴于这个模式太常见,我觉得就不用废话,画图啥的统统免了吧,直接上代码


父类

package zl.study.designpattern.proxy;public interface Graphic {public void render();public void store();public void load();public void resize();}

子类


package zl.study.designpattern.proxy;public class Image implements Graphic{protected int width,length;private String file;public Image(String file){this.file = file;}@Overridepublic void load() {this.width = 4;this.length = 8;}@Overridepublic void render() {long start = System.currentTimeMillis();try{Thread.sleep(100);}catch(Exception e){;}long end = System.currentTimeMillis();System.out.println("this operation elapse:"+ (end -start));}@Overridepublic void resize() {}@Overridepublic void store() {System.out.println(width +""+ length);}}

代理

package zl.study.designpattern.proxy;public class ImageProxy implements Graphic{private int width,length;private Image image;private String file;public ImageProxy(String file){this.file = file;}@Overridepublic void load() {if( null == image){image = new Image( file);}this.length = image.width;this.width = image.width;}@Overridepublic void render() {image.length = length;image.width = width;image.render();}@Overridepublic void resize() {width *= 2;length *=2;}@Overridepublic void store() {image.length = length;image.width = width;}}

测试类

package zl.study.designpattern.proxy.test;import zl.study.designpattern.proxy.Graphic;import zl.study.designpattern.proxy.ImageProxy;public class ProxyTest {public static void main(String args[]){String fileName = "ha.txt";Graphic image = new ImageProxy(fileName);image.load();image.resize();image.render();}}