设计模式之静态代理模式实战
轉(zhuǎn)載自?設(shè)計(jì)模式之靜態(tài)代理模式實(shí)戰(zhàn)
靜態(tài)代理模式很簡(jiǎn)單,代理類和實(shí)現(xiàn)類都實(shí)現(xiàn)相同的接口,然后通過代理類來(lái)調(diào)用實(shí)現(xiàn)類的方法。
如我們想保存用戶信息之前打印用戶信息,或者保存用戶信息之后把這些信息緩存下來(lái),即在運(yùn)行方法前后插入執(zhí)行一個(gè)別的操作,下面是一個(gè)簡(jiǎn)單的示例。
用戶接口
public interface?UserInterface?{
? ? boolean saveUser(User user);
}
用戶接口實(shí)現(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
通過代碼實(shí)戰(zhàn)的方法學(xué)習(xí)設(shè)計(jì)模式,是不是覺得靜態(tài)代理很簡(jiǎn)單了?
下面問題來(lái)了,如果我們想把用戶接口內(nèi)所有的方法都要代理,那我們所有的方法都要代理一遍,又或者之后又添加了新的方法,那又得重新寫代理,十分麻煩,明天分享下動(dòng)態(tài)代理的實(shí)現(xiàn),解決了靜態(tài)代理的不便擴(kuò)展性。
總結(jié)
以上是生活随笔為你收集整理的设计模式之静态代理模式实战的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联想台式电脑分类是怎么分的?
- 下一篇: Interaction triggers