First, the agent mode
Proxy mode is a common Java design pattern, characterized by proxy class and delegate class have the same interface, Agent class is mainly responsible for the delegation class preprocessing messages, filtering messages, forwarding messages to the delegate class, and afterwards processing messages.
There is usually an association between a proxy class and a delegate class, the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but rather provides a specific service by invoking the methods associated with the object of the delegate class.
By the time the agent was created, the proxy classes could be divided into two categories:
Static proxies: Created by a programmer or by a specific tool to generate source code and compile it. The. class file for the proxy class already exists before the program is run.
Dynamic Agent: When the program is running, it is dynamically created by using the reflection mechanism.
second, a single static agent
Copy Code code as follows:
public interface Countdao
{
View Account method
public void Querycount ();
}
public class Countdaoimpl implements Countdao
{
public void Querycount ()
{
System.out.println ("View account Method ...");
}
}
public class Counttrancproxy implements Countdao
{
Private Countdao Countdao;
Public Countproxy (Countdao Countdao)
{
This.countdao = Countdao;
}
@Override
public void Querycount ()
{
System.out.println ("Tranc start");
Countdao.querycount ();
System.out.println ("Tranc end");
}
}
public class Testcount
{
public static void Main (string[] args)
{
Counttrancproxy countproxy = new Counttrancproxy (new Countdaoimpl ());
Countproxy.updatecount ();
}
}
Tranc start
View Account Method ...
Tranc End
third, multiple static agents
Based on the above code, add the
Copy Code code as follows:
public class Countlogproxy implements Countdao
{
Private Countdao Countdao;
Public Countlogproxy (Countdao Countdao)
{
This.countdao = Countdao;
}
@Override
public void Querycount ()
{
System.out.println ("Log start");
Countdao.querycount ();
System.out.println ("Log end");
}
}
The calling code becomes the
Copy Code code as follows:
Embodies the idea of aggregation, the combination of agents between
public static void Main (string[] args)
{
Counttrancproxy trancproxy = new Counttrancproxy (new Countdaoimpl ());
Countlogproxy Logpro = new Countlogproxy (trancproxy);
Logpro.querycount ();
}
Log start
Before transaction processing
View Account Method ...
After the transaction is processed
Log End
Iv. Summary
In fact, you can use the proxy class can inherit or implement interface two ways to achieve the effect of the agent, but when multiple proxy classes need to be combined, the inheritance is not flexible, the need to constantly rewrite the proxy class, and the way to implement the interface is very easy to pass the aggregation of the combination of proxy classes.