常用設計模式總結--代理模式

代理模式就不廢話了,這個模式在生活中很常見,打官司、租房子的都需要找個專業的人來替你處理不擅長的事。

鑑於這個模式太常見,我覺得就不用廢話,畫圖啥的統統免了吧,直接上代碼


父類

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();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章