mercredi 28 février 2018

Recursive callback to a virtual metod

I'm implementing the composite design pattern and I notice that I have many traversals with code duplication.

For example:

class Composite extends BaseComposite{

    LinkedList<BaseComposite> objs;

    public BaseComposite foo(int id){
        for(BaseComposite obj : objs){
            if(obj.getId() == id){
                return obj;
            }
            BaseComposite tmp = obj.foo(id);
            if(tmp != null){
                return tmp;
            }
        }

        return null;
    }

    public BaseComposite bar(int id){
        for(BaseComposite obj : objs){
            if(obj.getId() == id){
                return obj;
            }
            BaseComposite tmp = obj.bar(id);
            if(tmp != null){
                return tmp;
            }
        }

        return null;
    }
}

class Leaf extends BaseComposite{
    public BaseComposite foo(int id){
        if(this.id == id){
            return this;
        }
        return null;
    }

    public BaseComposite bar(int id){
        return null;
    }
}

Is there a way to prevent this code duplication in the Composite class?

Aucun commentaire:

Enregistrer un commentaire