ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Minimalist Abstract Observer | 289

applied to all subclasses, a change to the superclass will do the trick. All changes are


inherited by the subclasses.


The biggest disadvantage attributed to inheritance isbreaking encapsulation. This


occurs where a subclass is changed because a parent class changes. The change may


break certain functionality of the subclass. (Other actions unrelated to inheritance


can break encapsulation, but they’re not relevant here.) Another disadvantage of


inheritance is the inheritance of unwanted features. Subclasses are stuck with the full


set of features from the parent class, and, as was seen in Chapter 4, overrides are


used to solve this problem. Finally, because inheritance occurs at compile time, you


cannot change the implementations from the parent class at runtime. All of these dis-


advantages reduce flexibility.


One advantage of object composition is the flip side of the main disadvantage of


inheritance—maintaining encapsulation. Object composition focuses on what each


object in the object set does, and its relationship to other objects. By focusing on


clear and limited tasks for each class (object), keeping encapsulation intact is better


and simpler. The focus changes from how something works to the relationship


between objects, and because each object comes to be dependent on others, object


encapsulation and reliability are more important and central.


By having securely encapsulated and focused objects, your number of classes is likely


to be larger, and that fact is a disadvantage of object composition. However, these


small focused classes also mean small hierarchies, and instead of inheriting andbeing


a feature of the object, composition allows one object tohave afeature of another


object.


The Observer design pattern uses object composition instead of inheritance. The two


major interfaces and concrete classes are eithersubjectorobserver. Together, these


objects arecomposed to create the overall model for the software design.


Minimalist Abstract Observer


To launch an Observer application using the minimum essentials, we need only two


interfaces and two classes, reflecting the model in the class diagram (Figure 8-2):



  • A subject interface

  • An observer interface

  • A concrete subject

  • A concrete observer


Keeping the overall goal in mind to centrally distribute state information, the con-


structs boil down to a subscribing method, an unsubscribing method, a notification


method for the subject, and an update method for the observer. The key to making

Free download pdf