代理模式

代理模式介绍:http://www.runoob.com/design-pattern/proxy-pattern.html

个人理解:代理模式相当于用B类代替A类行使一些A类的功能,B类具有但不完全具有A类的功能。B类有点类似于A类的子类。

代理模式的意图是为其他对象提供一种代理以控制对这个对象的访问。

 1、创建一个接口

public interface Image {
       void display();
}

 2、创建实现接口的实体类。

public class RealImage implements Image {
   private String fileName;
 
   public RealImage(String fileName){
      this.fileName = fileName;
      loadFromDisk(fileName);
   }
 
   @Override
   public void display() {
      System.out.println("Displaying " + fileName);
   }
 
   private void loadFromDisk(String fileName){
      System.out.println("Loading " + fileName);
   }
}
public class ProxyImage implements Image{
   private RealImage realImage;
   private String fileName;
 
   public ProxyImage(String fileName){
      this.fileName = fileName;
   }
 
   @Override
   public void display() {
      if(realImage == null){
         realImage = new RealImage(fileName);
      }
      realImage.display();
   }
}

 3、当被请求时,使用 ProxyImage 来获取 RealImage 类的对象。

public class ProxyPatternDemo {
    public static void main(String[] args) {
      Image image = new ProxyImage("test_10mb.jpg");
      image.display();
   }
}

代理模式和工厂模式明显的区别在于:

代理模式创建出来的对象只拥有原对象的部分功能,而工厂模式创建出来的对象具有原对象的全部功能。

原文地址:https://www.cnblogs.com/jwen1994/p/9983123.html