JAVA static proxy pattern explanation and example application

  • 2020-05-17 05:37:31
  • OfStack

JAVA static proxy pattern

Proxy pattern (Proxy) : provides a proxy for other objects to control access to this object.

The proxy pattern is simply a representation of the "real object," introducing a degree of indirection in accessing objects that can be used for multiple purposes.

Before the implementation code 1 simple life story, we all know that around us there are a lot of company have a sale or rental of housing, such as HOME LINK (LianJia), but HOME LINK itself does not exist any actual housing assets, he has sold the lease are need to house property owner (HomeMaster), to achieve the company's housing needs; At the same time, the business of selling houses and renting houses required by the company's employees (Seller). However, to realize this method, the employees must be authorized by the company and use the company's business resources to complete the task. At this point in the story, it should be clear that Seller is actually a static proxy in the proxy pattern, so let's start writing the code for this pattern (the business logic before and after the proxy implementation method is omitted here) :


interface LianJia{//LianJia Provide the channel method of housing sales (company business) 
  public void sellHouse();
}
class HomeMaster implements LianJia{// The homeowner needs to sell the house through HOME LINK (to realize the business channel of the company) 
  public void sellHouse(){
    System.out.println(" I have a house for sale ");
  }
}
class Seller implements LianJia{// HOME LINK business needs Seller implementation 
  private LianJia lj;// Statement HOME LINK company (understood as having to prove this seller Is HOME LINK), which makes it easy to call methods 
  public Seller(LianJia lj){
    this.lj = lj;
  }
  public void sellHouse(){
    lj.sellHouse();// The actual implementation requires invoking the company's business channel methods 
  }
}
public class ProxyMode{
  public static void main(String[] args){
    HomeMaster hm = new HomeMaster();
    Seller s = new Seller(hm);// Acting on behalf of the homeowner to realize the need to sell the house 
    s.sellHouse();
  }
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: