The idea behind composition over inheritance (COI) is that the behavior of an object can be altered by assigning it modular sub-objects, and redirecting the flow of execution to them. This is in contrast to the traditional object oriented approach of sub-classing the object and overriding or extending its behavior.
Both strategies have their benefits and consequences. Sub-classing is intuitive, and is the easiest to debug with existing tools. However, sub-classing only allows objects to evolve in one direction. If you have three different products (which are already sub-classed separately), and you want to add a common behavior to all of them, you are forced to sub-class all three, adding the same code to each.
COI would solve this by creating one new behavior, and assigning it to all three. This allows objects to evolve orthogonally: one modified behavior can be applied to many, otherwise unrelated objects.
The consequence is that it is slightly more complex to understand than simply looking at a class definition. The class can tell you that a behavior exists, and what its interface is. But, since a specific behavior isn't assigned until run time, it requires more effort to determine the expected behavior of an individual object.
Within the Material Handling Abstract, the base class for products is MhSnapper
(or sometimes MhSnapperInfo
). While it is not invalid to sub-class MhSnapper
, it is intended that behavior should change by adding a number of MhSnapperBehavior
s to it. Furthermore, the MhSnapper
only contains the minimum amount of state required for it to exist in the drawing. This includes things like position, rotation, and family relationships with other Snapper
s. All other information is stored in a MhSnapperShape
.
Comments
0 comments
Please sign in to leave a comment.