Chapter 12 -- State

[Previous] [Next]

Chapter 12

When multiple classes implement the same interface, each class defines distinct characteristics and behavior for the interface properties and methods. For example, both Golden Retrievers and Chihuahuas are distinct types of canines; from a software perspective, Canine is an interface that both the GoldenRetriever class and the Chihuahua class implement. Through the Canine interface, a client application could invoke the various methods that represent what canines do, such as bark, eat, run, and sleep. As you would expect, the behavior of these methods is unique between different classes—the amount of food a Chihuahua eats will normally be significantly different from the amount of food a Golden Retriever eats. Depending on the nature of the class, behavior within the same class might also be unique if the class is state sensitive. For example, canines, like most organic life forms, are sustained by a constant source of energy. Energy levels are maintained through a sufficient amount of food, exercise, rest, and so on. Level of energy is a state recognized by all classes of canine. Hunger is a substate of energy since it directly affects energy levels. When your pet Golden Retriever is hungry, possibly all behavioral patterns are altered. Moreover, the longer your Golden Retriever remains food deprived, the more apparent his change in behavior becomes. The same would be true for other canines such as Chihuahuas.

How do we account for such behavior changes in object-oriented development? The most common approach would be to use conditional language constructs within the interface method implementation of a class. These constructs determine the behavior to execute based on the state of the class implementation, which is represented by class member variables. Here's an example:

 ' Class Chihuahua Implements Canine Private m_iHungerLevel As Integer  Private Sub Canine_Bark( ) Select Case m_iHungerLevel Case 0 To 50 MsgBox "Happy Bark" Case 51 To 100 MsgBox "Agitated Bark" Case Is > 100 MsgBox "Unhappy Bark" End Select End Sub 

As long as the class behavior isn't extremely sensitive to state changes, this approach is a sensible solution. The longer the list of accountable state conditions, the more complex and cumbersome this approach becomes. To avoid this complexity, consider using the State design pattern described in this chapter.



Microsoft Visual Basic Design Patterns
Microsoft Visual Basic Design Patterns (Microsoft Professional Series)
ISBN: B00006L567
EAN: N/A
Year: 2000
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net