Tuesday, June 12, 2007

Access form controls freely

Sometimes we want to access form controls outside the normal scope. For example, a callback function in another file need to notify some control so it can update its display. Simply change the control from private to public is not enough, we also need to get the current form instance. According to the article How to get current ApplicationContext instance at run time, we can create a new class MyForm which inherits Form class and set a similar static field _myForm. The static field will always store the first instance of that class, even if that class is initialized multiple times later.

We then use this new class to run the application:

Application::Run(new MyForm());

Later on, whenever we want to get the instance of MyForm, we can do this:

MyForm* myForm = (new MyForm())->_myForm;

Although this method may not deserve the word "pattern", it is interesting to compare it to the Singleton Pattern. Different from Singleton Pattern, we can have more than one instance in this case, but we can freely get the first instance.

1 comment:

Xiaoguang said...

This is actually the case where the Singleton Pattern works perfectly. This way we don't even bother to create another instance every time.