Java - 用策略实现迭代器

时间:2017-11-12 22:11:27

标签: java design-patterns iterator composite strategy-pattern

我正在尝试为复合类实现自定义迭代器,并在迭代器实现中使用不同的策略,具体取决于客户端想要遍历复合结构的方式。

var data = {
    before: {  
          //your before data

    },
    after: {

        //your after data
     }
  };
testFireStoreEvent(data);

我想传递一个public class MyComposite implements Iterable<MyComponent> { ArrayList<MyComponent> childComponents; //MyComposite methods @Override public Iterator<MyComponent> iterator() { return new MyIterator(this); } } 对象作为迭代器构造的一部分,但是MyIteratorStrategy接口不允许将对象传递给Iterable方法。

iterator

以下是我在迭代器实现中如何使用策略:

public class SomeClient {
    private void traverseComposite() {
        MyComposite myComposite = new MyComposite();

        MyIteratorStrategy fooStrategy = new MyIteratorStrategy("foo");
        MyIteratorStrategy barStrategy = new MyIteratorStrategy("bar");

        MyIterator fooIterator = myComposite.iterator(fooStrategy);
        MyIterator barIterator = myComposite.iterator(barStrategy);     
    }
}

我试图学习如何利用设计模式,所以也许我过于笼统。如何将策略干净地注入迭代器?

1 个答案:

答案 0 :(得分:0)

MyIterator更改为实施Iterable<MyComponent>的类,而不是Iterator。 (为清楚起见,您可能希望将其重命名为MyComponentScanner。)

public Iterator<MyComponent> iterator()方法从MyComposite类移到MyIterator(或重命名的任何内容)。

示例...

public class MyComponentScanner implements Iterable<MyComponent> {

    MyComponent component;
    MyIteratorStrategy strategy;

    public MyComponentScanner(MyComponent component, MyIteratorStrategy strategy) {
        this.component = component;
        this.strategy = strategy;
    }

    @Override
    public Iterator<MyComponent> iterator() {
        return new Iterator() {
            @Override
            public Component next() {
                if(strategy.isDone(component) {
                    //return some child component
                } else {
                    //return some other child component
                }
            }
        };
    }

    //rest of implementation
}