Java Dynamic Agent Pattern Agent: A role represents another role to achieve certain specific functions.
For example: the relationship between manufacturers, middlemen, and customers. When customers buy products, they do not directly deal with the manufacturer, nor do they know how the products are produced. Customers only deal with middlemen, and middlemen can The products are packaged and some after-sales services are provided.
The agent pattern has three roles: 1. Abstract subject role 2. Agent subject role 3. Actual agent role
Let's take a look at the reality of a static proxy.
I'll take a tank as an example.
Abstract theme role: Moveable
public interface Moveable {
void move();
}
public class TanktimeProxy implements Moveable{
private Moveable t;
public TanktimeProxy(Moveable t) {
super();
this.t = t;
}
@Override
public void move() {
long time1 = System.currentTimeMillis();
System.out.println("time1="+time1);
t.move();
long time2 = System.currentTimeMillis();
System.out.println("time2="+time2);
System.out.println("The running time is:"+(time2-time1));
}
}
public class Tank implements Moveable{
@Override
public void move() {
System.out.println("TanK moving.....");
}
}
public class TestTank {
public static void main(String[] args) {
Tank t = new Tank();
Moveable move = new TanktimeProxy(t);
move.move();
}
}
Next I want to add a diary before and after TanK's move() method:
I have to write another class to implement this functionality:
public class TanklogProxy implements Moveable{
private Moveable t;
public TanklogProxy(Moveable t) {
super();
this.t = t;
}
@Override
public void move() {
System.out.println("start move.....");
t.move();
System.out.println("end move......");
}
}
public class TestTank {
public static void main(String[] args) {
Tank t = new Tank();
Moveable move = new TanktimeProxy(t);
Moveable movet = new TanklogProxy(move);
movet.move();
}
}
If I want to add more functions before and after the move() method of Tank is called, do I need to write more agent theme roles? This will make the code too fat and difficult to maintain. Is there any way? What method can be used to solve it? The answer is yes. We can dynamically generate agent theme roles to proxy all proxy objects. This is dynamic proxy.
At the end of the article, I would like to share with you some joke quotes from programmers: IBM and Boeing 777
The Boeing 777 is the first aircraft ever designed and manufactured entirely in computer virtual reality, using equipment entirely provided by IBM. Before the test flight, the president of Boeing enthusiastically invited IBM's technical director to participate in the test flight, but the supervisor said: "Ah, it's a great honor, but it's my wife's birthday that day, so..."...
The CEO of Boeing became angry when he heard this: "Coward, I haven't told you the date of the test flight yet!"