首页 > 其他 > 详细

适配器方法惯用法

时间:2020-07-04 12:26:09      阅读:59      评论:0      收藏:0      [点我收藏+]

如果现有一个Iterable类,你想要添加一种或多种在foreach语句中使用这个类的方法,应该怎么做?

一种解决方案是所谓的适配器方法的惯用法。“适配器”部分来自于设计模式,因为你必须提供特定的接口以满足foreach语句。当你有一个接口并需要另一个接口时,编写适配器就可以解决问题。这里,希望在默认的前向迭代器的基础上,添加产生反向迭代器的能力,因此不能使用覆盖,而是添加一个能够产生Iterable对象的方法,该对象可以用于foreach语句。

 

import java.util.*;

class ReversibleArrayList<T> extends ArrayList<T>{
    public ReversibleArrayList(Collection<T> c) {super(c);}
    public Iterable<T> reversed() {
        return new Iterable<T>() {
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    int current = size() - 1;
                    public boolean hasNext() {return current > -1;}
                    public T next() {return get(current--);}
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
}

public class AdapterMethodIdiom {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ReversibleArrayList<String> ral = new  
                ReversibleArrayList<String>(
                        Arrays.asList("To be or not to be".split(" ")));
        for(String s:ral)
            System.out.print(s+" ");
        System.out.println();
        for(String s:ral.reversed())
            System.out.print(s+" ");
    }

}

 

 

来自 Thinking in Java

 

适配器方法惯用法

原文:https://www.cnblogs.com/ConsidineJ/p/13234347.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!