Java设计模式(四) 装饰 代理模式

(七)装饰 Decorator

装饰是一个对象,以动态地增加一些新功能。

象与被装饰的对象须要实现同一个接口。装饰对象持有被装饰对象的实例。

interface DecoratorSourceable{
	public void method();
}
//被装饰类
class DecoratorSource implements DecoratorSourceable{
	public void method(){
		System.out.println("Source");
	}
}
//装饰类
class Decorator implements DecoratorSourceable{
	private DecoratorSourceable source;//这里是持有被装饰类。可是写为接口
	public Decorator(DecoratorSourceable source){
		this.source = source;
	}
	public void method(){
		System.out.println("before");
		source.method();
		System.out.println("after");
	}
}
public class DecoratorTest {
	public static void main(String[] args) {
		DecoratorSourceable source = new DecoratorSource();
		DecoratorSourceable decorator = new Decorator(source);
		decorator.method();
	}
}
须要扩展一个类的功能,或者想动态的为一个对象添加功能。还能动态的取消。可0以考虑用装饰模式。继承是静态的。不能动态添加或者删除。

借助装饰器模式。能够混合操作的不同变化。

经典的实例是输入输出流,能够从其它流组合成一个新的流。

装饰器模式还能够用来建立函数包装器。能依据有限的函数类集合创建大量的函数 对象。此外,借助装饰器模式能够灵活设计具有公共操作的类,这些公共操作往往具有不同的实现方式。

这样就能够再执行时集成新的混合的变化。

(八)代理模式

普通对象能够通过公共接口完毕自己须要完毕的工作。然后有些对象却因为某些原因无法履行自己的日常的职责。

比如有的对象载入时间过长,有的对象执行在其它计算机上面,或者须要拦截发送到对象的消息等。对于这些场景,我们能够引入代理对象,通过它承担client须要的职责。并将响应的请求转发给底层的目标对象。

interface ProxySourceable{
	public void method();
}
class ProxySource implements ProxySourceable {
	public void method(){
		System.out.println("Proxy method");
	}
}
class Proxy implements ProxySourceable{
	private ProxySource source;
	public Proxy(){
		super();
		this.source = new ProxySource();
	}
	public void method(){
		before();//能够加入新方法控制,或统计
		source.method();
		after();//能够改动结果
	}
	private void after(){
		System.out.println("after");
	}
	private void before(){
		System.out.println("before");
	}
}
public class ProxyTest{
	public static void main(String[] args){
		ProxySourceable source = new Proxy();
		source.method();
	}
}
使用场景:

已有方法使用时候须要对原有方法改进,直接改动原有方法违反了“对扩展开放,对改动关闭”原则。

採用代理类调用原来方法能够清奚分频功能。有助于后期维护。



版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4751905.html