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<Void>() {
                    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();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335