Thinking: The Class (Userdaoimpl) that others have written for the Userdao interface (you can't modify someone else's code), you need to log or check permissions on this class's methods to determine if other callers have permission to use the method. (or record call log)
Answer: You design a log class (Userdaologproxy), combine the Userdao (that is, userdaologproxy add a Userdao attribute), and then add all methods that are the same as the method name of the Userdao class. Add permission checks or log information to each method before you call Userdao the same method. The Userdaologproxy class that exposes to other callers is the class that has implemented the log check, and other callers can use the log function or permission function that you have implemented by Userdao U = new Userdaologproxy (). This is the proxy mode;
Instance:
Userdao Interface:
package com.shusheng.proxy;/**访问数据库的dao层*/publicinterface UserDao { //添加用户 publicbooleaninsert(User user);}
Userdaoimpl class:
package com.shusheng.proxy;/**假设这是时别人已经实现好的类*/publicclass UserDaoImpl implements UserDao{ /**将用户插入到数据库*/ @Override publicbooleaninsert(User user) { System.out.println("将user 插入到数据库中"); returntrue; }}
Proxy class:
PackageCom.shusheng.proxy;/** assumes that this is the Userdao proxy class that implements the logging of logs * / Public class userdaologproxy implements Userdao{Userdao Userdao;//Constructing proxy classes requires passing in the Proxied object Public Userdaologproxy(Userdao Userdao) { This. Userdao = Userdao; }@Override Public Boolean Insert(User user) { This. log ();//Record log returnUserdao.insert (user); }Private void Log() {System.out.println ("Logging"); }}
Test class (simulates upper-level caller):
package com.shusheng.proxy; /** This class can impersonate the service class that calls the Userdao class */ public class proxytest { public static void main (string[] args) {Userdao Userdao = new Userdaoimpl (); //not using a proxy, cannot log System.out.println (Userdao.insert (new User ()) + "\ n" ); Userdao = new userdaologproxy (Userdao); //proxy class logging System.out.println (Userdao.insert (new User ())); }}
(Implementing permission checks is the same.) )
the difference between a dynamic agent and a static proxy:
The above implementation is called static proxy, the agent can only proxy Userdaoimpl class, but similar to the spring framework is not possible to add static proxy for each class (which will cause the explosion of the class), so there is the concept of dynamic agent proxy, By passing the Proxied class into the proxy class, we can return a Proxied object, and the business of the proxy object implementation can be defined by itself (implemented in Invocationhandler). such as the implementation of permission checks, dynamic proxy mode in my blog also has a separate introduction, welcome to explore.
Proxy design pattern (structural type)