现在的位置: 首页 > 综合 > 正文

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

2014年02月23日 ⁄ 综合 ⁄ 共 1506字 ⁄ 字号 评论关闭

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

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

父类

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;
	}
	@Override
	public void load() {
		this.width = 4;
		this.length = 8;
		
	}
	@Override
	public 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));
		
	}
	@Override
	public void resize() {
		
	}
	@Override
	public 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;
	}
	
	@Override
	public void load() {
		if( null == image){
			image = new Image( file);
		}
		this.length = image.width;
		this.width = image.width;
	}
	@Override
	public void render() {
		image.length = length;
		image.width = width;
		
		image.render();
	}
	@Override
	public void resize() {
		width *= 2;
		length *=2;
	}
	@Override
	public 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();
	}
}

抱歉!评论已关闭.