I am trying to combine both pattern in java, but I did not understant how to make both of them nested?
1 Answers
It is very common to use the composite design pattern with visitor. Following is a class diagram of an example of application using visitor and composite design patters. The class diagram image
The application contains an interface Shape implemented by 2 concrete shapes (Circle and Rectangle). The Composite class allows to call the method accepte on all the shapes added in this class only by calling the method accept on the composite object.
Note: The composite object calls the visit method on itself also.
The composite class code:
public class Composite implements Shape {
Shape[] shapes;
public Composite() {
shapes = new Shape[]{new Rectangle(), new Circle()};
}
@Override
public void accept(ShapeVisitor shapeVisitor) {
for (int i = 0; i < shapes.length; i++) {
shapes[i].accept(shapeVisitor);
}
shapeVisitor.visit(this);
}
}
The PrintShape class (Implementation of the interface ShapeVisitor)
public class PrintShape implements ShapeVisitor {
@Override
public void visit(Composite composite) {
System.out.println("Printing composite ....");
}
@Override
public void visit(Rectangle rectangle) {
System.out.println("Print rectangle ...");
}
@Override
public void visit(Circle circle) {
System.out.println("Print Circle ....");
}
}
The Main test class:
public class VisitorMain {
public static void main(String[] args) {
Composite composite = new Composite();
composite.accept(new PrintShape());
}
}
Output: Print rectangle ... Print Circle .... Printing composite ....
I hope this will help.
For more information: here is the link Visitor design pattern

- 130
- 9