delphiinheritanceglobalsharelazarus

What is THE way to handle globaly shared Data/objects


After reading thousands of posts about how bad Global variables are, I got back to where I started from.

Here is a contrived example which I hope can explain my situation and my question:

i have an instance of TBuilding which needs to be accessed by every single other Class.

The TBuilding Class needs to be accessed by the Cars.

Should I make a global variable for the TCity and TBuilding instance, or is there anything else I can do ?

I tried to merge the TCity, TBuilding and TGarage classes, but that gives me headaches everytime I try.

Could some experienced people here lead me in the right direction?

I was about to create a Container Class, to share the needed instances between units. But after reading lots of posts, I wasn't sure that this was the correct way of dealing with this problem.

What about resourcestrings. Should I create a Container with reourcestrings which are shared amongst Classes. For Example if I have about 20 classes where I need the same string every time. The string needs to be translated, so I make a resourcestring out of it. Where do I collect such data?


Solution

  • You don't need any global variable for what you seem to be trying to achieve.

    All you need to do is store reference to parent class instance for each object.

    For instance you add another field called City to your TBuilding class and upon its creation you set reference to the TCity instance to which this building belongs.

    TBuilding = class(TObject)
    private
      FCity: TCity;
    protected
      ...
    public
      constructor Create(ACity: TCity);
      property City: TCity read FCity write FCity;
    end;
    
    ...
    
    constructor TBuilding.Create(ACity: TCity);
    begin
      inherited;
      FCity := ACity;
    end;
    

    Then do similar for TGarage, and TCar.

    By doing so you get ability to access Building object from a car object with something like this Car.Garage.Building.