Java 增强对象

Java增强对象,无非是为了让该对象具有更多的功能。Java增强对象主要有三种方式:继承、装饰者模式和动态代理。

一、继承

使得对象具有更多的功能,最最常用的方法就是继承。子类继承父类,便可拥有父类的属性和方法。
特点: 被增强的对象是固定的,增强的内容也是固定的。


二、装饰者模式

特点:被增强的对象是可以更换的,但是增强的内容是固定的
装饰者模式是指在不改变原类文件和功能的前提下,动态地扩展一个对象的功能。

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern. The decorator pattern is structurally nearly identical to the chain of responsibility pattern, the difference being that in a chain of responsibility, exactly one of the classes handles the request, while for the decorator, all classes handle the request. --WIKIPEDIA

简而言之,就是将通用功能放在装饰器中,在用到的时候进行调用。 下面举个例子:
1.定义一个接口

public interface interfaceA{
   public void function();
}

2.定义一个实现类

public class classA implements interfaceA{ 
    @Override
    public void function(){ 
        System.out.println("Here is in classA"); 
   }
}

3.定义一个装饰器

public class decorateA implement interfaceA{ 
   //定义一个变量,来接收不同的增强对象 
   private interfaceA a;
   public decorateA(interfaceA paramA){ 
      this.a = paramA; 
   }
   @Override public void function(){ 
      System.out.println("在调用被增强对象的方法之前,干些事情"); 
      a.function();
      System.out.println("在调用被增强对象的方法之后,干些事情"); 
    }
}

4.测试

public static void main(String [] args){ 
   classA a = new classA(); 
   a.function(); 
   decorateA decorate = new decorateA(a); 
   decorate.function(); 
}

解释:对于原来的类classA来说,并没有改变该类的属性和方法,只是将该类放在了decorateA【装饰器】中后,增强了原来的类的方法和属性。


三、动态代理

动态代理主要有jdk的动态代理和cglib动态代理,这里主要说jdk动态代理,cglib动态代理将会在下一篇博客里面介绍。
动态代理的特点:被增强的对象可以改变,增强的内容也可以改变
首先我们来回顾一下动态代理: jdk的动态代理主要是由一个Proxy类的静态方法newProxyInstance来实现的。

/** Returns an instance of a proxy class for the specified interfaces
     * that dispatches method invocations to the specified invocation
     * handler
     */
public static Object newProxyInstance(ClassLoader loader,
                                          Class[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        Objects.requireNonNull(h);

        final Class[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * Look up or generate the designated proxy class.
         */
        Class cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            final Constructor cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
        } catch (IllegalAccessException|InstantiationException e) {
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString(), e);
        }
    }

该方法其实就是根据传入的三个参数返回一个指定接口的代理类的实例。三个参数分别为:

  1. loader the class loader to define the proxy class【代理类的类加载器】
  2. interfaces the list of interfaces for the proxy class to implement【被代理对象所实现的接口】
  3. h the invocation handler to dispatch method invocations to【调用处理程序】
    其中InvocationHandler是一个接口,该接口下只有一个方法:
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;

在进行动态代理的时候,需要重载invoke方法。invoke方法处理代理实例上的方法调用并返回结果。 在与其关联的代理实例上调用方法时,将在调用处理程序上调用此方法。
下面给出一个实例:
1.定义一个接口:

public interface Teacher{
  public void teach();
}

2.定义两个增强的接口

public interface First(){
  public void first();
}

public interface Second(){
  public void second();
}

3.定义一个代理工厂类,来生成代理对象

@Data
public class AgentFactory{
  private Object target;
  private First first;
  private Second second;
  public Object getProxyInstance(){
     return Proxy.newProxyInstance(this.getClass.getClassLoader,
                                                     targer.getClass().getInterfaces(),
                                                     new InvocationHandler(){
        @Override
        public Object invoke(Object proxy, Method method, Object [] args) throws Throwable{
            //
            if(first != null){
               first.first();
            }
            if(second != null){
              second.second();
            }
            return method.invoke(targer,args);
            }
         });
  }
}

4.测试类

public static void main(String [] args){
  AgentFactory factory = new AgentFactory();
  factory.setTarger(new Teacher(){
     @Override
     public void teach(){
        System.out.println("Teach");
     }
  });
 factory.setFirst(new First(){
    @Override
    public void first(){
       System.out.println("First");
    }
 });
 factory.setSecond(new Second(){
    @Override
    public void second(){
      System.out.println("Second");
    }
 });
 Teacher teacher = (Teacher)factory.getProxyInstance();
 teacher.teach();
}

你可能感兴趣的:(Java 增强对象)