设计模式之静态代理模式实战
轉(zhuǎn)載自?設計模式之靜態(tài)代理模式實戰(zhàn)
靜態(tài)代理模式很簡單,代理類和實現(xiàn)類都實現(xiàn)相同的接口,然后通過代理類來調(diào)用實現(xiàn)類的方法。
如我們想保存用戶信息之前打印用戶信息,或者保存用戶信息之后把這些信息緩存下來,即在運行方法前后插入執(zhí)行一個別的操作,下面是一個簡單的示例。
用戶接口
public interface?UserInterface?{
? ? boolean saveUser(User user);
}
用戶接口實現(xiàn)
public class?UserInterfaceImpl?implements UserInterface {
? ? @Override
? ? public boolean saveUser(User user) {
? ? ? ? System.out.println("保存用戶: " + user.getName());
? ? ? ? return true;
? ? }
}
public class?Test?{
? ? public static void main(String[] args) {
? ? ? ? testStaticProxy();
? ? }
? ? private static void?testStaticProxy() {
? ? ? ? User user = new User();
? ? ? ? user.setName("tom");
? ? ? ? new StaticProxy(new UserInterfaceImpl()).saveUser(user);
? ? }
? ? static class StaticProxy implements UserInterface {
? ? ? ? private UserInterface userInterface;
? ? ? ? public StaticProxy(UserInterface userInterface) {
? ? ? ? ? ? this.userInterface = userInterface;
? ? ? ? }
? ? ? ? @Override
? ? ? ? public boolean saveUser(User user) {
? ? ? ? ? ? System.out.println("靜態(tài)代理-開始保存用戶");
? ? ? ? ? ? boolean result = userInterface.saveUser(user);
? ? ? ? ? ? System.out.println("靜態(tài)代理-保存用戶結(jié)果: " + result);
? ? ? ? ? ? System.out.println();
? ? ? ? ? ? return result;
? ? ? ? }
? ? }
}
結(jié)果輸出:
靜態(tài)代理-開始保存用戶
保存用戶: tom
靜態(tài)代理-保存用戶結(jié)果: true
通過代碼實戰(zhàn)的方法學習設計模式,是不是覺得靜態(tài)代理很簡單了?
下面問題來了,如果我們想把用戶接口內(nèi)所有的方法都要代理,那我們所有的方法都要代理一遍,又或者之后又添加了新的方法,那又得重新寫代理,十分麻煩,明天分享下動態(tài)代理的實現(xiàn),解決了靜態(tài)代理的不便擴展性。
總結(jié)
以上是生活随笔為你收集整理的设计模式之静态代理模式实战的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联想台式电脑分类是怎么分的?
- 下一篇: 电脑上如何关闭临时配置文件登录?