`
pouyang
  • 浏览: 313415 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Design Patterns 结构模式 之 Proxy 模式

阅读更多
Design Patterns  结构模式 之 Proxy 模式
1 Proxy

代理模式:给某一对象提供代理对象,并由代理对象控制具体对象的引用.

代理,指的就是一个角色代表另一个角色采取行动,就象生活中,一个红酒厂商,是不会直接把红酒零售客户的,都是通过代理来完成他的销售业务的.而客户,也不用为了喝红酒而到处找工厂,他只要找到厂商在当地的代理就行了,具体红酒工厂在那里,客户不用关心,代理会帮他处理.

代理模式涉及的角色:

1:抽象主题角色.声明了代理主题和真实主题的公共接口,使任何需要真实主题的地方都能用代理主题代替

2:代理主题角色.含有真实主题的引用,从而可以在任何时候操作真实主题,代理主题功过提供和真实主题相同的接口,使它可以随时代替真实主题.代理主题通过持有真实主题的引用,不但可以控制真实主题的创建或删除,可以在真实主题被调用前进行拦截,或在调用后进行某些操作.

3:真实代理对象.定义了代理角色所代表的具体对象.

代理模式的图:



1 公共接口
/**  
*抽象主题角色,定义了真实角色和代理角色的公共接口  
*/  
public interface SellInterface{   
     public Object sell();   
} 

2 真实角色 + 代理角色
/**  
*真实主题角色,这里指红酒工厂角色,它实现了SellInterface接口  
*/  
public class RedWineFactory implements SellInterface{   
     public Object sell(){   
         System.out.println("真实主题角色RedWineFactory 被调用了");   
         return new Object();   
     }   
}  
//////////////////////////////////////////////////////////////
/**  
*代理主题角色,这里指红酒代理商.它除了也要实现了sellInterface接口外,还持有红酒  
*厂商RedWineFactory 对象的引用,从而使它能在调用真实主题前后做一些必要处理.  
*/  
public class RedWineProxy implements SellInterface{   
     //持有一个RedWineFactory对象的引用   
      private RedWineFactory redWineFactory;  
     //销售总量   
      private static int count = 0;   
     public Object sell(){   
    	 doBefore();
    	 if (redWineFactory == null ) {
    		 redWineFactory = new RedWineFactory();
    	 }
    	 Object obj = redWineFactory.sell();
    	 doAfter();
    	 return obj;
     }   
  
     protected void doBefore() {
    	 System.out.println("售前服务!");
     }
     protected void doAfter() {
    	 System.out.println("售后服务 !");
     }
     
     public static void main(String agr[])   
     {   
          SellInterface sell = new RedWineProxy();   
          sell.sell();   
     }  

}  


2 java动态代理 + 代理模式

上面的代理,我们强迫代理类RedWineProxy实现了抽象接口SellInterface.这导致我们的代理类无法通用于其他接口,所以不得不为每一个接口实现一个代理类.幸好,java为代理模式提供了支持.
java主要是通过Proxy类和InvocationHandler接口来给实现对代理模式的支持的



通过上面的代码可以看出,代理主题ProxyObject类并没有实现我们定义的SellInterface借口,
而是实现了java的InvocationHandler接口,这样就把代理主题角色和我们的业务代码分离开来,使代理对象能通用于其他接口.
其实InvocationHandler接口就是一种拦截机制,当系统中有了代理对象以后,对原对象(真实主题)方法的调用,都会转由InvocationHandler接口来处理,并把方法信息以参数的形式传递给invoke方法,这样,我们就可以在invoke方法中拦截原对象的调用,并通过反射机制来动态调用原对象的方法.这好象也是spring aop编程的基础吧

3 超级简单AOP
图与代码不符


1, 切面
/**  
*切面接口,通过实现这个接口,我们可以对指定函数在调用前后进行处理  
*/  
public interface AopInterface {   
   public void before(Object obj);//调用的处理   
   public void end(Object obj);//调用后的处理   
}  
public class AopInterfaceImp implements AopInterface{   
    public void before(Object obj) {   
        System.out.println("调用前拦截");   
    }   
    public void end(Object obj) {   
        System.out.println("调用调用后处理");   
    }   
}  


2 具体的业务类
public interface ServiceInterface {   
    public void add(String value1,String value2);   
    public void acc(String value1);   
}   
public class ServiceImpl implements ServiceInterface{   
    public void add(String value1,String value2) {   
        System.out.println("ImpObject add(String value1,String value2)");   
    }   
    public void acc(String value1){   
        System.out.println("ImpObject acc(String value1)");   
    }   
} 


3 代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyObject2 implements InvocationHandler {   
    private AopInterface aop; //定义了切入时调用的方法   
    private Object proxy_obj; // 代理的具体对象  
    private String methodName;//指定要切入的方法名   
    ProxyObject2(){}   
    public Object factory(Object obj){   
        proxy_obj = obj;   
        Class cls = obj.getClass();   
        return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(),this);   
    }   
  
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {   
        if(this.aop == null)throw new NullPointerException("aop is null");   
        if(method == null)throw new NullPointerException("method is null");   
  
        Object o;   
        //如果指定了要拦截方法名,并且调用的方法和指定的方法名相同,则进行拦截处理   
        //否则当正常方法处理   
        if(methodName != null && method.toString().indexOf(methodName) != -1){   
            aop.before(proxy_obj);//指定方法调用前的处理   
            o = method.invoke(proxy_obj, args);   
            aop.end(proxy_obj);//指定方法调用后的处理   
        }else{   
            //没有指定的方法,以正常方法调用   
            o = method.invoke(proxy_obj, args);   
        }   
        return o;   
    }   
    public AopInterface getAop() {   
        return aop;   
    }   
    public void setAop(AopInterface aop) {   
        this.aop = aop;   
    }   
    public String getMethodName() {   
        return methodName;   
    }   
    public void setMethodName(String methodName) {   
        this.methodName = methodName;   
    }   
}  


4 测试
public class Main {
	public static void main(String agr[]){   
        ProxyObject2 po = new ProxyObject2();  // 代理 
        po.setAop(new AopInterfaceImp());      //我们实现的拦截处理对象   
        po.setMethodName("acc");//指定要拦截的函数   
        ServiceInterface si = (ServiceInterface)po.factory(new ServiceImpl());// 生成代理类
        //因为add方法不是我们指定的拦截函数,AopInterfaceImp是不会被执行   
         si.add("tt","dd");      
        //acc是我们指定的拦截方法,所以调用acc的前后会先执行AopInterfaceImp对象的两个方法      
         si.acc("tt");   
    }  
}



分享到:
评论

相关推荐

    Spring 5 Design Patterns

    This book will take you through Design Patterns and best practices required with the Spring framework. You will learn to use these design patterns to solve common problems when designing an ...

    Head First Design Patterns 英文版 Head First设计模式

    《Head First Design Patterns》共有14章,每章都介绍了几个设计模式,完整地涵盖了四人组版本全部23个设计模式。前言先介绍《Head First Design Patterns》的用法;第1章到第11章陆续介绍的设计模式为Strategy、...

    Design.Patterns.Explained.Simply

    We've tried hard to avoid both of these categories with Design Patterns Explained Simply. This book is fast and simple way to get the idea behind each of the 29 popular design patterns. The book is ...

    《Java Design Patterns》高清完整英文PDF版

    Learn how to implement design patterns in Java: each pattern in Java Design Patterns is a complete implementation and the output is generated using Eclipse, making the code accessible to all....

    Apress.Pro.Design.Patterns.in.Swift

    Pro Design Patterns in Swift shows you how to harness the power and flexibility of Swift to apply the most important and enduring design patterns to your applications, taking your development ...

    Beginning SOLID Principles and Design Patterns for ASP.NET Developers.pdf

    Beginning SOLID Principles and Design Patterns for ASP.NET Developers ■Chapter 1: Overview of SOLID Principles and Design Patterns ■Chapter 2: SOLID Principles ■Chapter 3: Creational Patterns: ...

    Learning Python Design Patterns(PACKT,2013)

    Then you will move on to learn about two creational design patterns which are Singleton and Factory, and two structural patterns which are Facade and Proxy. Finally, the book also explains three ...

    Head First Design Patterns

    Head First设计模式,非常经典的设计模式教程。 《Head First设计模式》共有14章,每章都介绍了几个设计模式,完整地涵盖了四人组版本全部23个设计模式。前言先介绍这本书的用法; 第1章到第11章陆续介绍的设计模式...

    Learning Python Design Patterns 2nd 2016第2版 无水印pdf 0分

    After this, we'll look at how to control object access with proxy patterns. It also covers observer patterns, command patterns, and compound patterns. By the end of the book, you will have enhanced ...

    Head First Design Patterns 高清英文版

    第1章到第11章陆续介绍的设计模式为Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton,Command、Adapter、Facade、TemplateMethod、Iterator、Composite、State、Proxy。最后三章比较...

    Design Patterns Elements of Reusable Object-Oriented Software

    • How Design Patterns Solve Design Problems • How to Select a Design Pattern • How to Use a Design Pattern A Case Study: Designing a Document Editor • Design Problems • Document Structure ...

    Head First Design Patterns 英文原版

    of Design Patterns so that you can hold your own with your co-worker (and impress cocktail party guests) when he casually mentions his stunningly clever use of Command, Facade, Proxy, and Factory in ...

    Selenium Design Patterns and Best Practices 最新 原版

    Stabilize your tests by using patterns such as the Action Wrapper and Black Hole Proxy patterns In Detail Selenium WebDriver is a global leader in automated web testing. It empowers users to ...

    Head First Design Patterns(英文,无水印,完整版)

    第1章到第11章陆续介绍的设计模式为Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton、Command、Adapter、Facade、Templat Method、Iterator、Composite、State、Proxy。*后三章比较...

    Packt.Go.Design.Patterns.2017

    Structural Patterns - Proxy, Facade, Decorator, and Flyweight Design Patterns Chapter 5. Behavioral Patterns - Strategy, Chain of Responsibility, and Command Design Patterns Chapter 6. Behavioral ...

    C++设计模式(Design Pattern)范例源代码

    23种设计模式(Design Pattern)的C++实现范例,包括下面列出的各种模式,代码包含较详细注释。另外附上“设计模式迷你手册.chm”供参考。 注:项目在 VS2008 下使用。 创建型: 抽象工厂模式(Abstract Factory) 生成...

Global site tag (gtag.js) - Google Analytics