Proxy Design Pattern

In Proxy pattern, a class represents functionality of another class. 

This type of design pattern comes under structural pattern. 

 

Below is the diagram and code for the example:

We are going to create an Image Interface and concrete classes implementing the Image interface.

ProxyImage is a proxy class to reduce memory footprint of RealImage object loading.

ProxyPatternDemo, our demo class, will use ProxyImage to get an Image object to load and display as it needs.

 

 

Detail code that achieves above diagram.

Step 1. Create the interface Image.java

public interface Image{
       void display();
}

Step 2. Create Concrete class implementing the same interface

public class RealImage implements Image{

   private String FileName;
   public RealImage(String fileName){

     this.FileName = fileName;

      loadFromDisk( fileName )
   }

  public void display(){
    System.out.println("Displaying+ " + FileName)
  }

  private void loadFromDisk(String fileName){
      System.out.println("Loading " + fileName);
   }

}

ProxyImage.java

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();
   }
}

Step 3

Use the ProxyImage to get object of RealImage class when required.

ProxyPatternDemo.java

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

      //image will be loaded from disk
      image.display(); 
      System.out.println("");
      
      //image will not be loaded from disk
      image.display();     
   }
}

 

转载于:https://www.cnblogs.com/codingyangmao/p/11275013.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值