![]() Both of the alternatives work almost the same way: one object has a reference to another and delegates it some work, whereas with inheritance, the object itself is able to do that work, inheriting the behavior from its superclass. Composition: object A consists of objects B A manages life cycle of B B can’t live without A. ![]() One of the ways to overcome these caveats is by using Aggregation or Composition Aggregation: object A contains objects B B can live without A. In most languages, inheritance doesn’t let a class inherit behaviors of multiple classes at the same time. Subclasses can have just one parent class.You can only replace the whole object with another one that’s created from a different subclass. You can’t alter the behavior of an existing object at runtime. However, inheritance has several serious caveats that you need to be aware of. You have to find some other way to structure notifications classes so that their number won’t accidentally break some Guinness record.Įxtending a class is the first thing that comes to mind when you need to alter an object’s behavior. However, it quickly became apparent that this approach would bloat the code immensely, not only the library code but the client code as well. You tried to address that problem by creating special subclasses which combined several notification methods within one class. Now the client was supposed to instantiate the desired notification class and use it for all further notifications.īut then someone reasonably asked you, “Why can’t you use several notification types at once? If your house is on fire, you’d probably want to be informed through every channel.” How hard can that be? You extended the Notifier class and put the additional notification methods into new subclasses. Others would like to be notified on Facebook and, of course, the corporate users would love to get Slack notifications.Įach notification type is implemented as a notifier’s subclass. Many of them would like to receive an SMS about critical issues. A third-party app which acted as a client was supposed to create and configure the notifier object once, and then use it each time something important happened.Ī program could use the notifier class to send notifications about important events to a predefined set of emails.Īt some point, you realize that users of the library expect more than just email notifications. The method could accept a message argument from a client and send the message to a list of emails that were passed to the notifier via its constructor. The initial version of the library was based on the Notifier class that had only a few fields, a constructor and a single send method. Imagine that you’re working on a notification library which lets other programs notify their users about important events.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |