最近在学习程序开发之设计模式,在网上找到一篇很不错的文章。这篇文章很详细地讲解了程序开发过程的中二十三中设计模式。文章链接如下:
http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html
我比较了代理模式与装饰模式,发现两者之间的区别很小:
相同点:
1. 两种模式都创建了一个接口;
2. 两种模式都创建了一个原始类并实现了上边的接口;
3. 两种模式都创建了另外一个类并实现上边的接口且将原始类作为其一个成员变量。 该类在代理模式中称为代理类, 而在装饰模式中成为装饰类
不同点:
1. 代理类中会添加额外的私有方法并被接口方法调用,可以在接口方法调用前和调用后对输入参数或输出结果加以控制;
2. 而装饰模式没有添加额外的私有方法,而是在接口方法中直接添加一些功能并调用成员对象的接口方法,以起到丰富成员对象的方法。
package com.design.pattern.structure.decorator;
public interface ISourceable {
public void method();
}
package com.design.pattern.structure.decorator.impl;
import com.design.pattern.structure.decorator.ISourceable;
public class Source implements ISourceable {
@Override
public void method() {
System.out.println("Source.....");
}
}
package com.design.pattern.structure.decorator.impl; import com.design.pattern.structure.decorator.ISourceable; public class Decorator implements ISourceable{ private ISourceable source; public Decorator(ISourceable source) { super(); this.source = source; } @Override public void method() { System.out.println("Before decorator"); this.source.method(); System.out.println("After decorator"); } }
代理模式代码:
package com.design.pattern.structure.proxy; public interface Sourceable { public void method(); }
package com.design.pattern.structure.proxy.impl; import com.design.pattern.structure.proxy.Sourceable; public class Source implements Sourceable { @Override public void method() { System.out.println("This is a original method!!"); } }
package com.design.pattern.structure.proxy.impl; import com.design.pattern.structure.proxy.Sourceable; public class Proxy implements Sourceable { private Source source; public Proxy(Source source) { super(); this.source = source; } @Override public void method() { before(); source.method(); after(); } private void before() { System.out.println("Do something before calling the original method"); } private void after() { System.out.println("Do something after calling the original method"); } }