java使用匿名类直接new接口

翻看Vector代码的时候,看到这么一段。java

/**
     * Returns an enumeration of the components of this vector. The
     * returned {@code Enumeration} object will generate all items in
     * this vector. The first item generated is the item at index {@code 0},
     * then the item at index {@code 1}, and so on.
     *
     * @return  an enumeration of the components of this vector
     * @see     Iterator
     */
    public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;


            public boolean hasMoreElements() {
                return count < elementCount;
            }


            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

 

 Enumeration是个接口,内部定义此处不缀述。this

此处用到了这种new接口的使用方法,若是有些场合,只须要临时须要建立一个接口的实现类,上面的"技巧"能够用来简化代码.
在结合接口内部的方法设定,便可实现强大的处理方式,而省去不少单独处理逻辑问题。

咱们在仔细看,会发现实现的接口实例中并无elementCount,而elementCount是在Vector中定义的,那么若是调用该方法,返回一个接口实例,在使用该接口实例的时候,如何获取到该值?
因而写一个demo查看下,

会发现返回的实例里面维护了一个包含v实例成员变量的实例指向。因此在其方法实现里面能够使用到该值。(至于其如何实现的为探究,读到此文知道的读者能够留言,谢谢)设计

那么会想,是否返回一个对象都会封装一个此类指向呢,能够本身按照此种方式写一个试试。3d

Car是一个接口,按照上述方式模式实现的,存在上述所说引用;Student并无。code

总结:component

一、适当的时候巧用返回接口实例方式,可结合模式方式实现某种功能简化;对象

二、是否能够利用其引用处理某些问题,什么样的修饰符的成员变量能被引用对象实现,这种设计的初衷考虑哪些等等,值得神经的时候思考下。blog

三、另外new 接口方式能够当作参数传递。如t.inject(new Car(){接口

  接口实现方法;element

});

相关文章
相关标签/搜索