SOLID OOP Design – OOP Design Pattern Representing All SOLID Principles

cjavaobject-orientedobserver-pattern

I'm trying to teach an object oriented design principles course (on SOLID) at a training institute. I also want to teach the students a few OOP design patterns such as factory, singleton and one other. I know there is no 1 to 1 match between SOLID principles and OOP Design patterns, but I want to introduce the students a pattern that is sort of inclusive of all the SOLID design principles at play.

Any ideas?

I'm really trying to fit in the observer pattern but want to keep it conforming with all the SOLID principles.

Best Answer

One of the most popular design pattern among the community here is the strategy pattern. And yes, if you build some example code around this pattern, you can demonstrate all the SOLID principles:

  • S = is fulfilled when each strategy subclass is only responsible for exactly one task, and the "context" class does not take responsibilities which belong into the strategy classes
  • O = you can add new strategies afterwards ("open for extentions") without the need to change the internals of the context ("closed for modifications")
  • L = this means to implement the strategy subclasses correctly with the semantics defined by the strategy interface, not changing the semantics in any of the subclasses. LSP would not be fulfilled when a subclass implements the strategy interface in a manner which breaks the parts of the context using the strategy.
  • I = is fulfilled when the strategy base class offers only a small, single-purpose interface (like the one "execute" method)
  • D = the context relies completely on the abstract strategy interface, it gets the concrete strategy "injected" from outside (for example, at construction time) and does not make any assumptions about, for example, a fixed set of subclasses, or the availability of specific subclasses.

Note that the pattern itself does not guarantee your code to be SOLID, it is more that the SOLID principles help you to implement the pattern correctly. You may consider to show your students not only correct examples for applying the SOLID principles, but also counter-examples in context of a strategy pattern, showing code which breaks each of the five principles. Or even better: make this an exercise for them.

Related Topic