zoukankan      html  css  js  c++  java
  • Proxy

    Spring中使用Proxy模式很多,经典就是AOP中的代理了,但是这里想讨论的是我们在自己的代码中实现代理模式的问题。

    Spring实现factory模式中,我们需要使用Person里面的方法,但是type是程序运行的过程中才知道是多少,如果要使用Person接口需要在代码里面动态的判断到底使用哪种对象,这时候使用Factory模式就很难实现这种了。
    撇开配置,我们最直接的想法是

        public interface Handler{
             int handler( int type);
        }
    
        public class Handler1 implements Handler{
             int handler(int type){
                  return type +1;
             }
        }
    
        public class Handler2 implements Handler{
             int handler(int type){
                  return type +2;
             }
        }
    
        public class TestHandler{
             private Handler handler;
    
             public void testhandler(){
                  int type = (int) random();          
                  if(type == 0){
                       handler = new Handler1();
                  }else{
                       handler = new Handler2();
                  }
                  handler.handler(type);
             }
        }
    

    这种代码使用Proxy模式是合适的。

    Proxy模式[http://en.wikipedia.org/wiki/Proxy_pattern] :所谓的代理者是指一个类型可以作为其它东西的接口。
    我们可以将PersonHandler 里面的person使用prox的方式来实现。

        public class HandlerProxy implements Handler{
             int handler(int type){
                  int type = (int) random();          
                  if(type == 0){
                       handler = new Handler1();
                  }else{
                       handler = new Handler2();
                  }
                  return handler.handler(type);
             }
        }
    
        public class TestHandler{
             private Handler handler = new HandlerProxy();
    
             public void testhandler(){
                  int type = (int) random();          
    
                  handler.handler(type);
             }
        }
    

    这样在配时就可以采用如下配置

        <bean id="handler1" class="Handler1" />
        <bean id="handler2" class = "Handler2"/>
    
        public class HandlerProxy implements Handler{
    
             @Autowired          
             private Handler handler1
             @Autowired     
             private Handler handler2
             int handler(int type){
                  int type = (int) random();          
                  if(type == 0){
                       return handler1.handler(type);
                  }else{
                       return handler2.handler(type);
                  }
    
             }
        }
  • 相关阅读:
    Objective--C三大特性:封装,继承,多态(零碎笔记)
    零碎的知识点
    Objective--C之《文件操作》练习代码
    Objective--C的Foundation frame之NSMutableDictionary代码
    Objective--C的Foundation frame之NSMutableArray代码
    Objective--C随笔2016年8月7日
    关于OC中的委托delegate
    javascript 绝对路径工具类
    IE 弹出框处理经验
    InputStream和OutputStream 何时使用
  • 原文地址:https://www.cnblogs.com/LiuB/p/6210391.html
Copyright © 2011-2022 走看看