Okay, so in my studying yesterday I went over the concept of Inheritance and how it applies to classes. Today I’m going over composition, which is an alternative to inheritance and is another way to create relationships between objects and combine simple objects into more complex ones. Inheritance and Composition are called design patterns and they can be used as templates for your code.
With inheritance, we think of one class as the parent and another class as the child. The child has all of the attributes and methods that the parent has, but sometimes the child is different from the parent so we can use the super class to override an inherited method.
With composition, it’s more like one class is a car and another is a steering wheel or an engine. The car is a complex object and it is made up of objects of a similar type. With composition, you build up the functionality of a class through other classes.
Another important design pattern is the Factory. A Factory is pattern that manufactures other objects. This pattern is modeled as a Factory class, module or method. Factory methods can create objects without specifying which class the object will belong to. They let the class who implement the factory method decide which object belongs to which class. Factory methods rely on inheritance.
So when do you use composition and when do you use inheritance?
Use composition to package up code into modules that is used in many different unrelated places and situations. If you are unsure, default to using composition.
Use inheritance only when there are clearly related reusable pieces of code that fit under a single common concept, or if you have to because of something you’re using.
So here’s my problem, I understand all of the above, but I’m still not 100% sure how to connect my factory method to the rest of my code so that it works. I understand the include method, but I’m still confused. I think that will be something that I need to talk to a DBC coach or teacher about. Look for edits once I figure it out!
- Design Patterns in Ruby
- Practice Object-Oriented Design in Ruby (POODR)
- Factory method pattern – Wikipedia
- Design Patterns: Elements of Reusable Object-Oriented Software – PDF