Which design pattern could be used for a shape editor? Visitor pattern in use for now

﹥>﹥吖頭↗ 提交于 2020-01-06 21:22:37

问题


In hindsight of my question from earlier about the usage of the visitor pattern for a shape editor I came to the conclusion that I have to break the design rules of it.
Mainly because I need to update my Shape fields, so essentially I need to pass arguments back to the visitor.

Right now I am population the UI fields with the variables of the ShapeObject.

public class Editor implements ShapeVisitor{

    private Shape shape;

    @Override
    public Foo visit(CircleObject circle) {
          // populate fields
          shape = circle;
          ((CircleObject) shape).getText().setCaption("test");
    }

    @Override
    public void visit(RectangleObject rectangle) {
          // populate fields
           shape = new RectangleObject();
    }


    public void setComponent(JsonArray arguments){
      Element element = getFromJson(arguments);
      element.getAttrs().accept(this);
    }
}

Somewhere in my code I have a Save Button which should update the ShapeObject.

        @Override
        public void buttonClick(ClickEvent event) {
                    element.setAttrs(shape);    
        }

Basically what I am doing is that I create a new Instance of a ShapeObject and update the fields there. Then I pass it to the element back via element.setAttrs(shape).


Essentially I would not need the visitor pattern at all, because I could achieve the same with the instanceof operator in the setComponent method. I am trying my best to avoid this operator, because in the near future I will have way more ShapeObjects then these two. I am not really sure if this is the approach I should take or maybe there is a even better one for a custom shape editor.

Best regards.


The Shape class looks like this with the visitor pattern

public abstract class Shape {
    public abstract void accept(ShapeVisitor v);

    public interface ShapeVisitor{
        public void visit(CircleObject circle);
        public void visit(RectangleObject rectangle);
    }
}

The approach with instanceof would be this

public void setComponent(JsonArray arguments){
      Element element = getFromJson(arguments);
      if(element.getAttrs() instanceof RectangleObject)
        shape = new RectangleObject;
    }

来源:https://stackoverflow.com/questions/34000755/which-design-pattern-could-be-used-for-a-shape-editor-visitor-pattern-in-use-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!