JAVA static proxy

Eg:

  1. Abstract an action, such as eating dinner
public interface DoSomeThing {

    void eatDinner();
}

Copy the code
  1. As a human being, we have to implement the act of eating dinner, so
Public class DoSomeThingImpl implements DoSomeThing{@override public void eatDinner() {system.out.println (" start eating dinner "); }}Copy the code
  1. We are taught to wash our hands before eating (new logic is suddenly needed in the business), we can modify the logic of eatDinner(), but we can also use a proxy class to add or modify a step before eating
public class DoSomeThingProy implements DoSomeThing{ private DoSomeThingImpl doSomeThing; Public DoSomeThingProy(DoSomeThingImpl doSomeThing) {this.dosomething= dosomething; } @override public void eatDinner() {system.out.println (" wash your hands "); doSomeThing.eatDinner(); //todo can also gargle after eating //xxxxx.xxxxx(); }}Copy the code
  1. test
public class DoSomeThingTest { public static void main(String[] args) { DoSomeThingImpl doSomeThing=new DoSomeThingImpl(); DoSomeThingProy doSomeThingProy=new DoSomeThingProy(doSomeThing); doSomeThingProy.eatDinner(); }} Output: Wash your hands and start eating dinnerCopy the code

Without modifying the original code, new actions can be added before or after the original action through a proxy class

  • Advantages: The static proxy mode extends the function of the target object without changing the target object.
  • Disadvantages: Static proxies implement all methods of the target object. Once the target interface adds methods, both the proxy object and the target object need to be modified accordingly, increasing maintenance costs.