|
|||||||||||||||
|
Delegate Form Behavior to a State Object
You can use the State behavior pattern with a context of any complexity, but I wouldn't necessarily employ it for every form. In fact, as a rule I wouldn't employ it for contexts with very low complexity. However, it is easier to demonstrate with a simple example and the implementation principle doesn't change as size increases.
In this demo, a simple customer form accepts a name and an email address (see Figure 1). The form has two modes: edit and browse. In edit mode, you can modify the value of the controls and update and delete records. In browse mode, you can only view a record. The controls are all disabled. Typically, you might use a flag to manage mode, and all of the code would exist in the form itself. In this example, you delegate the behavior of the form to a state object. As shown in Listing 1, the form refers to an instance of a class named BaseState. The BaseState object is an instance of either EditState or BrowseState. The precise behavior is dependent on the specific instance of a class that implements BaseState. All that the form has to do (only when the state changes) is determine which state the form is in and create that state object. Listing 1: The Form's code is implemented in terms of a state object. Listings 2, 3, and 4 show BaseState, EditState, and BrowseState, respectively. Listing 2: The BaseState interface
Listing 3: The EditState class implements BaseState and "turns" editing capability on.
Listing 4: The BrowseState class implements BaseState but "turns" editing capability off.
Because VB6 classes are interfaces, you have to implement every member of BaseState. You also have to do this because Form1 sends the same message regardless of state. However, it is the implementation of specific properties and methods, depending on state, that determines what happens. A useful feature of the State pattern is that you can change the behavior of the form by defining new states. (Figure 2 presents a UML visualization of the relationship between the Form and state classes.) Bare in mind that .NET supports dynamic assembly loading. This ultimately means you can load state behavioral classes dynamically and can easily add new states without recompiling a deployed application by using a .config file to indicate which states are present or should be loaded and by deploying new state assemblies only. This level of extensibility is probably impossible if not very difficult in VB6.
|
|||||||||||||||
|