博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java设计模式(四) 装饰 代理模式
阅读量:6951 次
发布时间:2019-06-27

本文共 1813 字,大约阅读时间需要 6 分钟。

(七)装饰 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();	}}
使用场景:

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

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

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

你可能感兴趣的文章
在aspx页面中使用三元表达式
查看>>
iOS定位和位置信息获取
查看>>
Debian 7 安装Firefox
查看>>
ajax模式 同步和异步
查看>>
我喜欢的vs code快捷键for mac
查看>>
sql表的复制问题
查看>>
es6的新内容
查看>>
Java教程
查看>>
跟着大神学zookeeper分布式锁实现-----来自Ruthless
查看>>
vue2.0 兼容ie9及其以上
查看>>
Xml中SelectSingleNode方法,xpath查找某节点用法
查看>>
JAVA - JAVA编译运行过程
查看>>
计时器setInterval
查看>>
iOS开发个人开发账号的证书详细使用及介绍
查看>>
尺取法
查看>>
Your APP_BUILD_SCRIPT points to an unknown file: ./jni/Android.mk
查看>>
NOIP-珠心算
查看>>
使用crypt配置Basic Auth登录认证
查看>>
sklearn
查看>>
linux命令系列目录
查看>>