jeudi 26 octobre 2017

How to get the entity attributes/enum from child with parent as reference?

The purpose of the design should be that client will be able to call getAttribute() method without knowing if the dynamic object is from parent class or any of its child class.

Code compiled here is in a rudimentary stage.

Attribute Definitions

interface AttributeDefinition{

}

public class AbstractAsset<T extends AttributeDefinition>{
   protected T attribute;
   protected AbstractAsset(T attribute){
      this.attribute = attribute;
   }
   public T getAttribute(){
      return this.attribute;
   }
}
enum AssetAttribute implements AttributeDefinition{
   ASSET_ID,  
   CREATED_TIME
}
enum VehicleAssetAttribute implements AttributeDefinition{
   VIN,
   MAKE
}
enum MobileAssetAttribute implements AttributeDefinition{
   SIM_NO,
   IMEI
}

Entities

class Asset extends AbstractAsset<AssetAttribute>{
   public Asset(AssetAttribute){
     super(AssetAttribute);
   } 
}
class Vehicle extends AbstractAsset<VehicleAssetAttribute>{
  public Vehicle(VehicleAssetAttribute){
     super(VehicleAssetAttribute);
  }
}
class Mobile extends AbstractAsset<MobileAssetAttribute>{
  public Mobile(MobileAssetAttribute){
    super(MobileAssetAttribute);
  }
}

Factory

public class AssetFactory
{
   public Asset constructAsset(String assetType){
    if(assetType.equals("vehicle")){
      return new Vehicle(new VehicleAssetAttribute());
    }else if(assetType.equals("mobile"){
      return new Mobile(new MobileAssetAttribute());
    }
   }
}

This is what I have been trying to arrive at.

  1. A factory that takes in the argument of type, instantiates the child object, and "must" return that through a parent reference

  2. My client will only use the parent entity retrieved from the factory and get the dynamic(child) object's attribute.

  3. Also, require inheritance of attributes - i.e. VehicleAttribute, MobileAttribute would also have AssetAttribute's value.

Client

Row row = new Row();
Asset asset =  AssetFactory.constructAsset("vehicle");
row.set(asset.getAttribute().ASSET_ID, "xyz"); 
row.set(asset.getAttribute().CREATED_TIME, 12345); 
row.set(asset.getAttribute().VIN, TN23);
DO.persist(row);

Couple of points

  1. Not desirable for the client to hard code the attribute, construction of specific asset should be taken care of by the asset factory.
  2. AssetFactory will take multiple parameters - assetType, region for instantiating the specific asset
  3. A similar hierarchy will exist for the region also. (Vehicle - VehicleIN, VehicleCH)

I would appreciate if there is anything we could do to achieve the desired outcome.

Aucun commentaire:

Enregistrer un commentaire