501 - not implemented
501 - not implemented

Reputation: 2698

How to set up different parameter in a Composite Pattern?

for my develop i want to use the component-pattern because a component is part of another component.

But there is one problem. The components need different parameters in the run-function (which must be implement).

Does someone have a idea how to realize it?

Example:

   public abstract class componsite{
       Componente(){...}
       public void run(Object object1){......}
  }
  public class firstComponent extends composite{
       ....
       public void run(Object object1){......}
       @Override
  }
  public class secondComponent extends composite{
       ....
       @Override
       public void run(Object object1,Different Object object2){......}
  }

Greetz

Upvotes: 1

Views: 461

Answers (2)

Adamski
Adamski

Reputation: 54725

Consider using the Visitor pattern. This allows for an elegant strongly typed solution that avoids type checking using instanceof or downcasting.

public interface ComponentVisitor {
  void visitFirstComponent(FirstComponent fc);

  void visitSecondComponent(SecondComponent sc);
}

public class ComponentVisitorImpl implements ComponentVisitor {
  public void visitFirstComponent(FirstComponent fc) {    
    fc.firstComponentSpecifiedMethod(a, b, c);
    // Make a call *back* to FirstComponent passing in appropriate parameters.
  }
}

Then within each Component's run() method you simply call the relevant visitor method which will then make a call back into the component with the relevant parameters; e.g.

public class FirstComponent extends Component {
  public void run(ComponentVisitor cv) {
    cv.visitFirstComponent(this);
  }
}

The drawback of this approach is that the logic can be difficult to follow.

Upvotes: 2

Brett Walker
Brett Walker

Reputation: 3586

Use Java's Varargs as part of the Composite interface

public class secondComponent extends composite{
   ....
   @Override
   public void run(Object... object){......}
}

Upvotes: 2

Related Questions