设计模式-装饰模式&代理模式

继续上一篇

装饰模式

动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活

在这里插入图片描述

Component是定义一个对象接口,可以给这些对象动态地添加职责

ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责

Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的

ConcreteDecorator就是具体的装饰对象,起到Component添加职责的功能

Component类
public abstract class Component {
	public abstract void Operaion();
}

ConcreteComponent类
public class ConcreteComponent extends Component {

	@Override
	public void Operaion() {
		// TODO Auto-generated method stub
		System.out.println("具体对象的操作");
	}

}

Decorator类
public abstract class Decorator extends Component {
	protected Component component;
	//设置Component
	public void SetComponent(Component component){
		this.component=component;
	}
	//重写Operation(),实际执行的是Component的Operation()
	public void Operation(){
		if(component!=null){
			component.Operaion();
		}
	}
	
}

ConcreteDecoratorA类
public class ConcreteDecoratorA extends Decorator {

	
	//本类的独有功能,以区别于ConcreteDecoratorB
	private String addedState;
	@Override
	public void Operaion() {
		// TODO Auto-generated method stub
		super.Operation();
		addedState="new State";
		System.out.println("具体装饰对象A的操作");
	}

}

ConcreteDecoratorB类

public class ConcreteDecoratorB extends Decorator {

	@Override
	public void Operaion() {
		// TODO Auto-generated method stub
		super.Operation();
		AddedBehavior();
		System.out.println("具体装饰对象B的操作");
	}
	//本类的独有的方法,以区别于ConcreteDecoratorA
	private void AddedBehavior(){
		
	}

}

当需要在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂
而装饰模式却提供了很好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象。

代理模式

为其他对象提供一种代理以控制对这个对象的访问

在这里插入图片描述

Subject 类
public abstract class Subject {
	public abstract void Request();
}
RealSubject类
public class RealSubject extends Subject {

	@Override
	public void Request() {
		// TODO Auto-generated method stub
		System.out.println("真实的请求");
	}
	
}
Proxy类
public class Proxy extends Subject {
	
	RealSubject realSubject;
	@Override
	public void Request() {
		// TODO Auto-generated method stub
		if(realSubject==null){
			realSubject=new RealSubject();
		}
		realSubject.Request();
	}
	
}

客户端
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Proxy proxy=new Proxy();
		proxy.Request();
	}

}

适应场景

第一. 远程代理,也就是为一个对象在不同的地址空间提供局部代表,这样可以隐藏一个对象存在于不同地址空间的事实
第二. 虚拟代理,是根据需要创建开销很大的对象,通过它来存放实例化需要很长时间的真实对象
第三. 安全代理,用来控制真实对象访问时的权限
第四. 智能指引,是指调用真实的对象时,代理处理另外一些事

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值