Hello everyone!
I assume that it is possible to implement strategy pattern with inheritance. So what is pros and cons of both ways?
Thanks!
@jrg.developer Can you please help with this when you get a chance? Thank you - much appreciated! :]
Thanks for your question, @observerward. :]
Yes, it is indeed possible to implement the strategy pattern with inheritance. You simply replace the strategy protocol with an “abstract” class instead. There are, of course, pros and cons to this approach:
Pros
- A class can have stored properties, which a protocol cannot have.
- A class can subclass another concrete class, which a protocol cannot do.
Cons
-
“Abstract” classes don’t actually exist in Swift/Objective-C/iOS. Consequently, it’s possible for a consumer to pass in an instance of the “abstract” type directly, which is perfectly legal from the compiler’s standpoint but basically guaranteed to cause problems at runtime.
-
Consumers are forced to subclass the “abstract” type, which may be difficult or impossible if an existing class already subclasses another type. There are other patterns that help with this – see Adapter for example – but it just make things a bit more difficult, perhaps unnecessarily.
With these limitations in mind, you might wonder, “Should I always prefer protocols, then?” Not necessarily.
I generally would prefer protocols over classes for implementing the strategy pattern, but at times, it’s either not feasible or much harder. For example, if your strategy requires a lot of properties, or you’re required to subclass an Objective-C class (such as interacting with legacy and/or Apple code), then you may be better off using an “abstract” class than a protocol.
As with most programming problems, the final answer really depends on the details! Analyze your situation, and make good choices.
I hope this answer helps. If you need more clarity here, let me know. :]
Oh, thank you for explanation!