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

本文深入探讨代理模式在日常生活中的应用,通过实例代码展示如何使用代理模式处理不擅长的任务,如打官司、租房子等。重点介绍了父类、子类及代理类的设计,以及如何在测试类中实现模式应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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


父类

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值