Wednesday 15 July 2015

java - instantiate a specific subtype depending on the constructor argument -


I case that four types of data objects: class DataTypeAlpha the data type class DataTypeBeta extends data type class DataTypeGamma extends data type class DataTypeDelta extends data type

and four different TreeNode type of GUI framework, specific to each one wrapped data type:

  class Alfred note expands MyAppTreeNode ...   

Now I have frequent patterns that I have an example of a datatype and should be a new instance of MyAppTreeNode. I give you two find solutions A:

  class datatype {// Instantiates and appropriate MyAppTreeNode for the DataType essence MyAppTreeNode createTreeNode (); }   

Solution two:

  class MyAppTreeNode {static MyAppTreeNode createTreeNodeForDataType (datatype) {if (datatype Instanceof DataTypeAlpha) New AlphaTreeNode return ((DataTypeAlpha) datatype) else if (datatype Instanceof DataTypeBety) return new BetaTreeNode ((DataTypeBeta) datatype) and that ... (and if throwing someone else ... new IllegalArgumentException); }} What does   

The solution uses a polymorphism, less is more "elegant" but I would have no idea about the GUI Framework datatype classes that I use. Maybe I can also use two separate GUI frameworks?

Do you see a third solution? I added the Gis tag for this question. Perhaps there are some functions in Geice or any other dependency injection library which can help here?

By looking at similar questions:

  • Of course I will use the factory pattern for this, but inside the factory I still have been left with the question.

    The visitor is induced approach for this as always in a datatype object in one Acceptable method, but unlike normal visitor patterns, it does not exceed children and will return a value. To avoid too much confusion, call the near object call to accept for the visitor rather than the operator . The accept and operator are a normal way to return.

    Then there will be something like this in the code data model

      public intangible class datatype {public abstract & lt; T & gt; Acceptance of T (operator & lt; T & gt; op); } Public Interface operator & lt; T & gt; {T-opera alpha (datatype alfa data); T Operate Beta (Datatype Beta Data); ...} Public category dataType alpha datatype {public & lt; T & gt; T accept (operator  op) {return op.operateAlpha (this); }} ....   

    and in GUI you have

      public square tree node factor equipment operator & lt; MyAppTreeNode & gt; {Public MyAppTreeNode powered alpha (datatype alfa data) {Returns new alpha-print (data); } ...} Public class MyAppTreeNode {Static Tree Node Factory Factory = ...; Static MyAppTreeNode createTreeNodeForDataType (DataType Datatype) {return dataType.accept (factory); }}    

No comments:

Post a Comment