"Android source design mode analysis and actual combat" reading notes (14)

Source: Internet
Author: User
Tags concurrentmodificationexception

14th, iterator mode

Iterator mode, also known as cursor mode, is one of the behavioral design patterns. We know that access to the container object is bound to involve a traversal algorithm, we can encapsulate the traversal method in the container, or do not provide a traversal method, let the person who uses the container to implement it themselves. Both of these situations seem to solve the problem.

In the former case, however, the container is overloaded with functionality, not only to maintain the elements within its own container (add, delete, etc.), but also to provide an interface to traverse itself, and because of the problem of traversing state preservation, multiple traversal of the same container object cannot be performed concurrently. The second approach is easy, but it exposes the inner details of the container.

Because of this, the iterator pattern comes into being, inserting a third-party-iterator between the client access class and the container body, which solves the above drawbacks well.

1. Definition

Provides a way to sequentially access individual elements in a container object without exposing the object's internal representation.

2. Usage Scenarios

When traversing a container object.

3. Simple implementation

Example of the book: Wang and Xiao Hui in the company's two business units, one day the boss to arrange tasks let them both statistics of their respective departments of employee data.

Employee Entity class:

 Public  class Employee {    PrivateString name;//Name    Private intAge//Age    PrivateString sex;//Gender    PrivateString position;//Jobs     Public Employee(String name,intAge, String sex, string position) {Super(); This. name = name; This. Age = Age; This. sex = sex; This. Position = position; }//Simplify code, omit setter and Getter methods    @Override     PublicStringtoString() {return "employee{"+"Name= '"+ name +' \ '+", age="+ Age +", sex="+ Sex +", position= '"+ Position +' \ '+"}"; }}

Xiao Hui Department:

 Public classCompanyhui {Privateemployee[] Array =Newemployee[3]; Public Companyhui() {array[0] =NewEmployee ("Brother Hui", -,"Male","Program Ape"); array[1] =NewEmployee ("Little Red", at,"Male","Program Ape"); array[2] =NewEmployee ("Little Fai", -,"Male","Program Ape"); } PublicEmployee[]GetEmployees(){returnArray }}

Wang Department:

 Public  class companymin {    Private List<Employee>List=NewArraylist<> (); PublicCompanymin () {List. Add (NewEmployee ("Wang", -,"Male","Program Ape"));List. Add (NewEmployee ("Small Yun", A,"female","Test"));List. Add (NewEmployee ("Small Square", -,"female","Test"));List. Add (NewEmployee ("The Child", +,"female","Design"));List. Add (NewEmployee ("lang sentiment", +,"female","Design"));//Spit A groove, why the Wang a man, Xiao Hui Department of all men. } Public List<Employee> GetEmployees () {return List; }}

Boss View:

 Public classBoss { Public Static void Main(string[] args) {Companyhui Hui =NewCompanyhui (); employee[] huilist = Hui.getemployees (); for(inti =0; i < huilist.length; i++) {System. out. println (Huilist[i]); } companymin min =NewCompanymin (); List minlist = Min.getemployees (); for(inti =0; I < minlist.size (); i++) {System. out. println (Minlist.Get(i). toString ()); }    }}

Results:

Employee{name=' hui elder brother ',  Age=, Sex=Male, position=' program Ape '}Employee{name=' Little Red ',  Age=at Sex=Male, position=' program Ape '}Employee{name=' Xiao Hui ',  Age=, Sex=Male, position=' program Ape '}Employee{name=' Wang ',  Age=, Sex=Male, position=' program Ape '}Employee{name=' Xiao Yun ',  Age=, Sex=Female, position=' Test '}Employee{name=' small square ',  Age=, Sex=Female, position=' Test '}Employee{name=' er ',  Age=, Sex=Female, position=' Design '}Employee{name=' lang love ',  Age=, Sex=Female, position=' Design '}

This seems to be no problem, but if there are multiple departments, each department has its own implementation, then we have to add the traverse logic in the Boss class, so that the boss class will be more and more functions, while exposing the internal details. Then we need to define an iterator interface:

publicinterface Iterator {    /**     * 是否还有下一个元素      *      * @return true表示有,false表示没有     */    boolean hasNext();    /**     * 返回当前元素,并将位置移至下一位     */    Object next();}

Wang's iterator:

 Public  class miniterator implements Iterator{    PrivateList<employee> list;Private intPosition Public Miniterator(list<employee> List) { This. list = list; }@Override     Public Boolean Hasnext() {return! (Position > List.size ()-1|| List.get (position) = =NULL); }@Override     PublicObjectNext() {Employee E = list.get (position); position++;returnE }}

Small FAI's iterator:

 Public  class huiiterator implements Iterator{    PrivateEmployee[] Array;Private intPosition Public Huiiterator(employee[] Array) { This. Array = array; }@Override     Public Boolean Hasnext() {return! (Position > Array.Length-1|| Array[position] = =NULL); }@Override     PublicObjectNext() {Employee e = array[position]; position++;returnE }}

Defining interfaces for container classes

publicinterface Company {    /**     * 返回一个迭代器对象     *      * @return 迭代器对象     */    Iterator iterator();}

Modify the previous two container classes:

 Public  class Companyhui implements Company {    Privateemployee[] Array =Newemployee[3]; Public Companyhui() {array[0] =NewEmployee ("Brother Hui", -,"Male","Program Ape"); array[1] =NewEmployee ("Little Red", at,"Male","Program Ape"); array[2] =NewEmployee ("Little Fai", -,"Male","Program Ape"); } PublicEmployee[]GetEmployees(){returnArray }@Override     PublicIteratoriterator() {return NewHuiiterator (array); }}
 Public  class companymin implements Company {    Private List<Employee>List=NewArraylist<> (); PublicCompanymin () {List. Add (NewEmployee ("Wang", -,"Male","Program Ape"));List. Add (NewEmployee ("Small Yun", A,"female","Test"));List. Add (NewEmployee ("Small Square", -,"female","Test"));List. Add (NewEmployee ("The Child", +,"female","Design"));List. Add (NewEmployee ("lang sentiment", +,"female","Design")); } Public List<Employee> GetEmployees () {return List; } @Override PublicIterator Iterator () {return NewMiniterator (List); }}

Boss View:

publicclass Boss {    publicstaticvoidmain(String[] args) {        new CompanyHui();        check(hui.iterator());        new CompanyMin();        check(min.iterator());    }    privatestaticvoidcheck(Iterator iterator){        while (iterator.hasNext()) {            System.out.println(iterator.next().toString());        }    }}

The result does not change, do not repeat write.

4.Android mode in the source of the implementation of 1.Cursor

When we query the database using the Sqlitedatabase's Query method, a cursor cursor object is returned, which is essentially a concrete iterator that we can use to traverse the result set of the database query.

5. Summary

Since the development of the iterator pattern, almost all high-level languages have built-in implementations, and for developers, it's very rare to implement iterators themselves, so this chapter is more about understanding than applying.

1. Advantages

(1) conform to the principle of single responsibility in object-oriented design.

(2) supports multiple traversal of the container object. The relationship between the container class and the traversal algorithm is weakened.

2. Disadvantages

(1) Increase in class files.

(3) A concurrentmodificationexception exception will occur.

(2) The traversal process is a one-way and irreversible traversal.

6. Reference

An iterative pattern for Java design patterns in layman's

Concurrentmodificationexception exception

"Android source design mode analysis and actual combat" reading notes (14)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.