jeudi 12 janvier 2017

Abstract class with Override method adding specific component

What is the best way to implement some classes that extend a abstract superclass, where each class always adds a component but the components may differ?

I define an abstract class which implements drag and drop behaviour and has a component to show and edit some field. The specific component differs, in some cases the field may be empty, there may be more then one fields and so on. In the abstract class i add the component via an abstract getComponent() method. Subclasses provide their own implementation. Subclasses use different fields either passed in the constructor or calculated from the parameters provided in the constructor.

These fields are not yet available in the superconstructor call, so the getComponent() method cannot be called at construction time in the abstract class. A workaroud is to add the Component in onInitialize(), or just leave it up to the implementing classes to add the component (or not?) but maybe the whole approach is a anti-pattern.

code snippet:

       public abstract class AbstractContainer extends Panel {

   AbstractContainer( String markupId, IModel<> somemodels ..) 
  {
       super( markupId );
       this.setOutputMarkupId( true );

       this.add( new DragDropBehavior( "result" ) {
       //some stuff
       });

       // cannot do this.add(getComponent()) here
       // implementations use fields that have not been set 
       // yet in child classes
   }

   abstract protected Component getComponent();
 }


    public class MyPanel extends AbstractContainer {
     IModel mySpecificFieldModel;

     MyPanel( String markupId, IModel<> somemodels, IModel mySpecificFieldModel)
   {
      super( somemodels );
      this.mySpecificFieldModel=mySpecificFieldModel;
   }

   protected Component getComponent() 
  {
       Component component = new MyComponent("id",  this.mySpecificFieldModel);
       return component;
  }
}

Aucun commentaire:

Enregistrer un commentaire