在代理模式(Proxy Pattern)中,一个类代表另一个类的功能。这种类型的设计模式属于结构型模式。
在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口。
核心:
优点:
缺点:
使用场景:
注意事项:1、和适配器模式的区别:适配器模式主要改变所考虑对象的接口,而代理模式不能改变所代理类的接口。 2、和装饰器模式的区别:装饰器模式为了增强功能,而代理模式是为了加以控制。
public interface Movable { void move(); }
public class AudiCar implements Movable{ @Override public void move() { System.out.println("AudiCar is moving cacaca...................."); } }
public class AudiCarTimeProxy implements Movable { private Movable thing; public AudiCarTimeProxy(Movable thing) { this.thing = thing; } @Override public void move() { long start = System.currentTimeMillis(); System.out.println("AudiCarTimeProxy move start "); try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { System.out.println("run exception"); } thing.move(); long end = System.currentTimeMillis(); System.out.println("AudiCarTimeProxy move end "); System.out.println("callback move 耗时为:"+(end-start)+"ms"); } } public class AudiCarLogProxy implements Movable { private Movable thing; public AudiCarLogProxy(Movable thing) { this.thing = thing; } @Override public void move() { System.out.println("AudiCarLogProxy move start"); thing.move(); System.out.println("AudiCarLogProxy move end"); } }
public class StaticProxyDemo01 { public static void main(String[] args) { new AudiCarTimeProxy(new AudiCarLogProxy(new AudiCar())).move(); System.out.println("--------------------------------------------------"); new AudiCarLogProxy(new AudiCarTimeProxy(new AudiCar())).move(); } }
AudiCarTimeProxy move start AudiCarLogProxy move start AudiCar is moving cacaca..................... AudiCarLogProxy move end AudiCarTimeProxy move end callback move 耗时为:402ms -------------------------------------------------- AudiCarLogProxy move start AudiCarTimeProxy move start AudiCar is moving cacaca..................... AudiCarTimeProxy move end callback move 耗时为:661ms AudiCarLogProxy move end
原文:https://www.cnblogs.com/vincentYw/p/12594450.html