描述
代理模式就是多一个代理类出来,替原对象进行一些操作
适用
如果已有的方法在使用的时候需要对原有的方法进行改进,此时有两种办法:
- 修改原有的方法来适应。这样违反了“对扩展开放,对修改关闭”的原则。
- 就是采用一个代理类调用原有的方法,且对产生的结果进行控制。这种方法就是代理模式。
使用代理模式,可以将功能划分的更加清晰,有助于后期维护!
其他
与装饰模式很相似,不同之处是在装饰模式中,实例化对象时会首先实例化一个目标类,然后实例化一个装饰类,之后装饰目标类(将目标类用作装饰类的对象);
代理对象是实例化时直接实例化的是代理对象,在代理类中默认会有一个目标类实例变量;
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| interface Source { public void name(); }
class Animal implements Source { @Override public void name(){ Test.printMsg("Animal.name"); }; }
class Proxy implements Source { private Source source; public Proxy(){ super(); this.source = new Animal(); } @Override public void name(){ before(); source.name(); after(); } public void before(){ Test.printMsg("before"); } public void after(){ Test.printMsg("after"); } }
public class Test { public static void printMsg(String msg){ System.out.println(msg); } public static void main(String[] args){ Source source = new Proxy(); source.name(); } }
|