接口是一种高度的抽象,里面会规定一些将要实现的行为。它比抽象类更加抽象,在由接口组成的继承层级中,从上往下看,是抽象到具体的过程,通过继承我们可以保留父接口定义的行为,同时对其可以做扩展。上一层是对下一层共性的抽象,下层是对上层不同维度的演进。我们以Java的集合框架为例:
从这个uml图可以看出,最上层只有一个Iterable接口,这里只是需要返回一个迭代器,它可以用来处理一些可以迭代的对象,可以在foreach或者while循环中迭代。那么哪些对象是可以迭代的呢?由此衍生出第二层接口,Collection,DirectoryStream接口都是可迭代的。 DirectoryStream源码以及使用实例:
val dirName = Paths.get("d:/usr");
val paths = Files.newDirectoryStream(dirName)
paths.forEach {
Log.d("tanyonglin", it.fileName.toString())
}
什么样的算是Collection,JDK给出定义Collection代表一组对象,称之为元素,有些集合允许元素重复,有些有序,有些无序,于是这些描述又衍生了下一层,Set,List,Queue,这是针对Collection中不同类型的集合的抽象定义, Set接口
public interface Set<out E> : Collection<E> {
// Query Operations
override val size: Int
override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean
override fun iterator(): Iterator<E>
// Bulk Operations
override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
}
以及List接口
public interface List<out E> : Collection<E> {
// Query Operations
override val size: Int
override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean
override fun iterator(): Iterator<E>
// Bulk Operations
override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
// Positional Access Operations
/**
* Returns the element at the specified index in the list.
*/
public operator fun get(index: Int): E
// Search Operations
/**
* Returns the index of the first occurrence of the specified element in the list, or -1 if the specified
* element is not contained in the list.
*/
public fun indexOf(element: @UnsafeVariance E): Int
```}
Queue接口
public interface List : Collection { // Query Operations
override val size: Int
override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean
override fun iterator(): Iterator<E>
// Bulk Operations
override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
// Positional Access Operations
/**
* Returns the element at the specified index in the list.
*/
public operator fun get(index: Int): E
// Search Operations
/**
* Returns the index of the first occurrence of the specified element in the list, or -1 if the specified
* element is not contained in the list.
*/
public fun indexOf(element: @UnsafeVariance E): Int
我们发现有很多不同的方法,这个就是对Collection不同维度的演进 。职责不断的细化,
接口继承有什么意义?
假如没有接口继承,那会怎么样?那么所有接口的方法就要放到一个接口中去,那么这个接口规定的行为就有点多了,既要负责返回一个迭代器,可以用来迭代。又要是一个集合,而且又要定义有序集合的行为,又要定义无序集合的行为,既要定义有重复元素的集合的行为,又要定义无重复元素的集合,通过接口继承产生的层级接口,层级分析,职责分明。通过接口继承,可以重新定义上层已经定义的行为,也不会影响到同一层级的其他接口中的行为。本质:对事物进行抽象的粒度是有粗细之分的。