Understanding the Strategy pattern

Christian Rolle
2 min readFeb 18, 2023

--

The overall objective of the Strategy pattern is similar to the Template Method pattern. Both are higher level behavioral patterns. Though the TemplateMethod pattern is heavily based on inheritance.
The Strategy pattern otherwise is aiming at defined interfaces.

Let’s evaluate with a code example. And Ruby is awesome with that.
The story goes about sharing an article and marking it as shared. First the problematic approach.

class Article
attr_accessor :text
attr_reader :title, :published_at

def initialize(title:)
@title = title
end

def share(publisher:)
case publisher
when :linked_in
TwitterAPI.new.release title: title, text: text
when :twitter
MediumAPI.new.release title: title, text: text
end
@published_at = Time.current
end
end

The problem is obvious. What if there should another publisher? Sharing the article and how to share is tightly coupled. Let’s unravel the knot with the Strategy pattern.
The idea behind is to move the sharing-API specifics into a strategy object and pass it to the article by dependency injection.

class Article
attr_accessor :text
attr_reader :title, :published_at

def initialize(title:)
@title = title
end

def share(publisher:)
publisher.release title: title, text: text
@published_at = Time.current
end
end

class MediumAPI
def release(title:, text:)
# the Medium API integration details
end
end

class LinkedInAPI
def release(title:, text:)
# the LinkedIn API integration details
end
end

With that it doesn’t matter how many social-media APIs ever will be wired. Just inject another strategy meaning another API integration. However article specifics like setting the publishing time still remains in the articles responsibility. By applying the Strategy a high degree of flexibility can be achieved.

article = Article.new title: 'Understanding the Strategy pattern'
article.text = 'The overall objective of the Strategy pattern ...'
article.share LinkedInAPI.new
article.published_at
# => Sat, 18 Feb 2023 07:10:01 UTC +00:00

The article even could be shared with MySpace if it was still around.

What this statement is trying to say by is separating the concerns the world out there may change but has little effect on the own implementation just by applying the proper pattern.

--

--

Christian Rolle
Christian Rolle

Written by Christian Rolle

#Ruby on Rails full stack web developer in the enterprise business with a passion for people. I am constantly blogging.

No responses yet