Chazu
Chazu

Reputation: 1018

Providing global configuration data to objects within a UI framework

I'm working on a text-based UI widget library, and have decided it's high time that I provide the ability for a user of my library to encapsulate application-wide configuration via an application object, like so:

class App:

    def __init__(self, screen_size_tuple):
        self.screen_size = screen_size_tuple

    def get_screen_size(self):
        return self.screen_size

class Widget:

    def __init__(self, rows, cols, y, x, foo, bar, app):
        self.rows = rows
        self.original_dimensions = (rows, cols)
        self.original_coords = (y, x)
        #etc, etc
        self.app = app
        self.fullscreen = False     

    def self.toggle_fullscreen(self):
        if self.fullscreen != True:
            self.y = 0
            self.x = 0
            self.rows = self.app.screen_size[0] # y value from the application object
            self.cols = self.app.screen_size[1] # x value from the application object
        else:
            self.y = self.original_coords[0]
            self.x = self.original_coords[1]
            self.rows = self.original_dimensions[0]
            self.cols = self.original-dimensions[1]

My question is two-fold: Firstly, when I employ this tactic, how can I avoid having to pass the instance of the App class to each widget upon creation? Is the best practice to delegate widget creation to the app object itself? Secondly, is there a name for this design pattern when properly employed? It seems like a bit like an observer or dependency injection, but I'm not certain those patterns apply here.

Thanks in advance =)

Upvotes: 0

Views: 107

Answers (1)

Amber
Amber

Reputation: 527033

If you want "application-wide but not global" configuration there are a few common patterns:

  1. Use your app object to create the widget objects, e.g. app.create(WidgetClass)
  2. Pass down the app through your widget hierarchy, like so:

a = App()

f = FrameWidget()
a.add(f) # sets FrameWidget's config to a's config

b = ButtonWidget()
f.add(b) # sets ButtonWidget's config to f's config, which happens to be a's

c = CheckboxWidget()
f.add(c) # sets CheckboxWidget's config to f's config, also a's

Upvotes: 1

Related Questions