美文网首页
JAVA: Implementing Collection En

JAVA: Implementing Collection En

作者: 刘煌旭 | 来源:发表于2017-03-21 00:12 被阅读0次

    Traditionally, we use loops to iterate collections:

    Loops Iterating List

    To traverse a Collection, we need to write some kind of loops: for-each, while-loop, etc. Writing all these loops is easy, but it soon becomes tedious, slowing down our coding process; And being tedious often means being error-prone. We must develop some way to solve the problem.

    Looking at these loops closely, we can easily discover that they can be divided into two parts: the code inside the loop and the loop that wraps the code inside it:

    The Anatomy of A Loop

    In the anatomy above, we can see that:

    1) Only the code inside the loop wrapper varies; 

    2) The loop, as a wrapper of the code inside it, remains the same, and thus can be factored out.

    With all these observations, I employed the so called Strategy Design Pattern and devised the following code:

    Enumeration v1

    class StopFlag is introduced as a communication mechanism between the enumeration method of interface Enumeration and its caller so the method can tell its caller to stop when appropriate.

    Working, but not so elegant, you might think. So did I. So after a second thought, I did some refinement and came up with the following code:

    Enumeration v2

    Here the revised version eliminates the StopFlag class, saving its job for the return value of the enumeration method.

    Future Refactor

    With the introduction of lambda, a new feature of JAVA SE 8, this strategy can be taken further to an extreme where the Enumeration interface and its anonymous inner class implementation can be removed. That way, the code can be even more compact.

    相关文章

      网友评论

          本文标题:JAVA: Implementing Collection En

          本文链接:https://www.haomeiwen.com/subject/hdtpnttx.html