dimanche 13 décembre 2015

Dynamically Casting class and calling appropriate methods

I am writing a utility which uses some classes defined in a 3rd party library which i do not control.

I would like the to know what would be a good way to handle situations like the one described below : 3rd party library has a base abstract class 'Food' which is extended by 'Appetizer','Entree',"Beverage' and 'Dessert'. (all part of 3rd Party Library)

I am writing a 'WaiterUtility' which has methods to serve each type of food. I want to avoid an endless chain of instanceof checks .


`

Class WaiterUtility{
   public serveItems(Food[] items)
   {
        for(Food aFood : items){
            //how do i call the sub-class specific methods i wrote below?
        }
    }
    private void serve(Appetizer aFood){//somecode}
    private void serve(Entree aFood){//somecode}
    private void serve(Beverage aFood){//somecode}
    private void serve(Dessert aFood){//somecode}
}

`





Aucun commentaire:

Enregistrer un commentaire