mercredi 10 juin 2020

Which pattern is best to use in the below scenario

I have a class it draws different shapes. For Circle and triangle data will be provided while creating the objects. But for a Rectangle the partial data is provided at creation of object and the partial data need to be fetched from different sources .

Interface IShape
{
  GetData();
  Draw();
}

class Circle : IShape
{    
    GetData();    
    Draw();    
}

class Triangle: IShape
{    
    GetData();
    Draw();    
}

class Rectangle: IShape
{    
    GetData();
    Draw();    
}

The rectangle needs to fetch data from one of the class which is using below interface.

Interface IRetrieveData
{    
    FetchPartialData();    
}

class GetFromDatabase : IRetrieveData
{    
      FetchRectangleData();    
}

class GetFromXML: FetchRectangleData
{    
    FetchPartialData();    
}

At runtime the Rectangle will know what object to use(XML/database/etc ). My question is whats the best way to use IRetrieveData object in Rectangle class. Is it a good idea to have the class like below.

class Rectangle: IShape
{    
    IRetrieveData dataObj;

    Rectangle()
    {
    if(someCondtion)
    dataObj = new GetFromDatabase();
    else
    dataObj = new GetFrmXML();            
    }

    GetData()
    {
    dataObj.FetchPartialData();
    }
    Draw();

}

Is there any design pattern I can apply here?

Aucun commentaire:

Enregistrer un commentaire