大话设计模式-迭代器模式-2020-10-22

2020-10-22  本文已影响0人  勇往直前888

定义

提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

结构图

image.png

使用场景

售票员的例子

abstract class Iterator {
    public abstract Object first();
    public abstract Object next();
    public abstract Boolean isDone();
    public abstract Object currentItem();
}
class ConcreteIterator extends Iterator {
    private ConcreteAggregate aggregate;
    private int current = 0;

    public ConcreteIterator(ConcreteAggregate aggregate) {
        this.aggregate = aggregate;
    }

    @Override
    public Object first() {
        return aggregate.objectAtIndex(0);
    }

    @Override
    public Object next() {
        current++;
        return aggregate.objectAtIndex(current);
    }

    @Override
    public Boolean isDone() {
        return (current >= aggregate.count) ? true : false;
    }

    @Override
    public Object currentItem() {
        return aggregate.objectAtIndex(current);
    }
}
abstract class Aggregate {
    public abstract Iterator createIterator();
}
class ConcreteAggregate extends Aggregate {
    private ArrayList<Object> items = new ArrayList<Object>();

    // 集合个数,只提供getter
    public int count;

    @Override
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }

    // 通过下标访问元素
    public Object objectAtIndex(int index) {
        if (index < count) {
            return items.get(index);
        } else {
            return null;
        }
    }

    // 添加元素
    public void add(Object object) {
        items.add(object);
        count = items.size();
    }
}
image.png
public class IteratorActivity extends AppCompatActivity {

    public static void launch(Context context) {
        if (null != context) {
            Intent intent = new Intent();
            intent.setClass(context, IteratorActivity.class);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_iterator);
        setTitle("迭代器模式");

        TextView ticketTextView = findViewById(R.id.textViewTicket);

        ConcreteAggregate aggregate = new ConcreteAggregate();

        aggregate.add("大鸟");
        aggregate.add("小菜");
        aggregate.add("行李");
        aggregate.add("老外");
        aggregate.add("公交内部员工");
        aggregate.add("小偷");

        ConcreteIterator iterator = new ConcreteIterator(aggregate);
        String message = "";
        while (!iterator.isDone()) {
            message += iterator.currentItem() + " ====== 请买车票"  + "\n";
            iterator.next();
        }
        ticketTextView.setText(message);
    }
}

Demo地址

https://gitee.com/zhangxusong888/Android/tree/master/design_pattern

上一篇下一篇

猜你喜欢

热点阅读