`
leonzhx
  • 浏览: 793515 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 20: Prefer class hierarchies to tagged classes

阅读更多

1.  You may run across a class whose instances come in two or more flavors and contain a tag field indicating the flavor of the instance. (i.e. An Operator class with one field to indicate what operation it does.)

 

2.  Such tagged classes have numerous shortcomings. They are cluttered with boilerplate, including enum declarations, tag fields, and switch statements. Readability is further harmed because multiple implementations are jumbled together in a single class. Memory footprint is increased because instances are burdened with irrelevant fields belonging to other flavors. You can’t add a flavor to a tagged class unless you can modify its source file. In short, tagged classes are verbose, error-prone, and inefficient. The tag could be eliminated and the class replaced by a hierarchy.

 

3.  To transform a tagged class into a class hierarchy, first define an abstract class containing an abstract method for each method in the tagged class whose behavior depends on the tag value. If there are any methods whose behavior does not depend on the value of the tag, put them in this class. Similarly, if there are any data fields used by all the flavors, put them in this class. Next, define a concrete subclass of the root class for each flavor of the original tagged class. Include in each subclass the data fields particular to its flavor. Also include in each subclass the appropriate implementation of each abstract method in the root class.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics