代理设计模式与装饰设计模式

本文深入探讨了代理设计模式与装饰设计模式的概念、原理及应用实例,通过具体的代码示例,清晰展示了如何使用代理模式实现复杂业务的简化处理,以及装饰模式如何为现有类动态添加功能。以租房业务为例,代理模式确保了用户只负责租到房子,而复杂的流程由代理处理;装饰模式则允许在不修改原有类的情况下为其添加新功能。

代理设计模式UML类图:  

 

代理设计模式是接口的应用之一,一个代理操作,一个真实操作。Runnable接口实现线程就是应用代理设计模式,如图:

以找中Jie租房为例的代理设计模式代码:

public class ProxyDemo {
	public static void main(String[] args) {
         //客户端不知道代理委托了另一个对象 RentHouse rent = new RentCompany(); rent.house("小心黑ZhongJie"); rent.house("租房贵"); } } interface RentHouse {//租房 public void house(String url); } class RealRent implements RentHouse { public void house(String url) { System.out.println("北京:" + url); } } class RentCompany implements RentHouse { private RentHouse r;//保存真正租房操作 public RentCompany() {
         //关系在编译时确定 this.r = new RealRent(); } public boolean check(String url) { if (url.contains("黑ZhongJie")) { System.out.println("不能租房"); return false; } return true; } public void house(String url) { if (this.check(url)) {// 通过检查了 this.r.house(url);//真实操作 } } }

  租房接口下有两个操作,一个真实租房操作,一个是中Jie公司。我们只需要租到房子就行,而租房的各种流程都交给中Jie公司处理,不用我们关心。即是说,代理操作处理复杂业务,真实操作处理核心业务,二者分开

装饰设计模式:

public class Client{
	public static void main(String[] args) {
          //客户端制定了装饰者需要装饰哪一个类
		Component c = new Decorator(new ConcreteDecorator());
		c.print("装饰");
		
	}
}
interface Component{
	public void print(String url);
}
//被装饰类 class ConcreteDecorator implements Component{ public void print(String url) { System.out.println("北京:" + url); } } //装饰类,可以为ConcreteDecorator类动态的添加一些功能 class Decorator implements Component{ private Component c; public Decorator(Component c) { this.c = c; } public void print(String url) {
         System.out.println("装饰前"); c.print();
         System.out.println("装饰后"); } }

输出结果:

装饰前
原始方法
装饰后

  

java io就是经典的装饰设计模式。

  PrintStream print = new PrintStream(new FileOutputStream());

  PrintStream操作的本质离不开OutputStream,只是将这个类的功能加强了

转载于:https://www.cnblogs.com/wujinsen/p/4630733.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值