简体   繁体   中英

Composite pattern: Copy tree structure

I have implemented a basic composite pattern structure having three classes:

class Component
{
};

class Leaf : public Component
{
};

class Composite : public Component
{
vector<Component> Leaves;
};

Furthermore, I have another class ComponentCollection as a container of Components. These classes all have a corresponding class responsible for the creation of the graphical representation:

class GraphicComponent;
class GraphicLeaf;
class GraphicComposite; 
class GraphicComponentCollection;

From a given tree structure composed of different Component objects, I want to create the corresponding graphical representation objects starting from an abstract method:

createGraphicRepresentations(Component a_Component);

Is there an elegant way to create either GraphicLeaf or GraphicComposite depending on a_Component while avoiding a type check?

You could delegate the creation of the graphical component back to the original component:

class Component {

    GraphicComponent create();
}

So you could implement a tree traverser which then calls create on every component. Thats one way. The other way is to implement a visitor pattern . With the visitor pattern your code would look something like this:

interface IComponentVisitor {

   void visit(Component component);
   void visit(OtherComponent component);
}

class Component {
  void accept(IComponentVisitor visitor) {
     visitor.visit(this);
  }
}

A concrete visitor then implements the visitor and creates the corresponding components.

class GraphicsVisitor {
  void visit(Component compoennt) {
  }
  void visit(OtherComponent component) {
     graphisComponent.add(new OtherGraphicsComponent());
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM