Design pattern of proxy mode-static proxy

1 What is the proxy mode

Proxy Pattern: Proxy Pattern is one of the common design patterns in Java. The so-called proxy mode means that the client does not directly call the actual object, but indirectly calls the actual object by calling the proxy object. Such as intermediary. As shown below
Insert picture description here

2 Why use proxy mode

Isolation: In some cases, a client class does not want or cannot directly refer to a delegate object, and the proxy class object can play an intermediary role between the client class and the delegate object. Its characteristic is that the proxy class and the delegate class implement the same Of the
interface.
The principle of opening and closing: In addition to being an intermediary between the client class and the delegate class, the agent class can also extend the function of the delegate class by adding additional functions to the agent class. In this way, we only need to modify the agent class without modifying the delegate. Class, in line with the opening and closing principles of code design.

3 Implement the proxy mode

The static proxy mode consists of three parts:

  • A public interface
  • A proxy role
  • An agent role

4 Code section

4.1 Create a public interface

public interface Rent {
    
     
		void renting(); // 租房方法
	}

4.2 Create a proxy role

public class Person implements Rent {
    
     
// 重写租房方法
@Override 
   public void renting() {
    
     
	System.out.println("某人 有房出租"); 
    } 
}

4.3 Create agent role

public class StaticProxy implements Rent {
    
     
	private Rent rent; 
	public StaticProxyRent(Rent rent){
    
     
		this.rent = rent; 
	}
	@Override 
	public void renting() {
    
     
		System.out.println("向房客出租房屋"); 
		this.rent.renting(); 
		System.out.println("完成售后服务"); 
	} 
}

4.4 Create a test class for testing

public class StaticProxyTest {
    
    
public static void main(String[] args) {
    
     
	Rent rent = new Person(); 
	StaticProxy staticProxy = new StaticProxy(rent); 	
	staticProxy.renting(); 
	} 
}

4.5 Running results
Insert picture description here

5 Summary

Let us summarize, in fact, the agency model is the relationship between the landlord, the middleman, and the renter. If the landlord has a house to rent, just find a middleman, and a middleman can have multiple landlords, which greatly reduces the pressure on the landlord and gives users more choices. Moreover, intermediaries can expand many services, such as property, entertainment, etc. However, static proxies have a big disadvantage. As the number of proxied objects increases, we find that the pressure on the proxied objects is increasing, and the code written in them is bloated.

Guess you like

Origin blog.csdn.net/wjf_jone/article/details/108910539