Search code examples
oopdesign-patternsooad

Different interpretation of internal state based on what client wants


A Model object which has some private internal state. A component of this state is exposed to the clients. But one of the clients wants a different component of the internal state to be exposed. How should this be dealt with?An example

public GarageModel {
    private Vehicle car;
    private Vehicle truck;

    public Vehicle getMostInterestingVehicle() {
        //exposes car as the most interesting vehicle but
        //one of the client wants this to return a truck
        return car;
    }
}

Solution

  • It is hard to say given your sample, you could apply a strategy pattern on your GarageModel class for each different client and override that single method to cater to each of their needs. This only works if you can provide different garage models to your clients though.

    Polymorphism is always the answer as a teacher of mine used to say

    An example would be

    public TruckGarageModel: GarageModel {
        public override Vehicle getMostInterestingVehicle(){
            return truck;
        }
    }
    
    public CarGarageModel: GarageModel {
        public override Vehicle getMostInterestingVehicle(){
            return car;
        }
    }
    

    Then you would pass the appropriate decorated version of your GarageModel to each different client