Skip to content

Instantly share code, notes, and snippets.

@cloudiosx
Created March 23, 2022 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudiosx/b4480b91025b2e5eee2b23d21605be6f to your computer and use it in GitHub Desktop.
Save cloudiosx/b4480b91025b2e5eee2b23d21605be6f to your computer and use it in GitHub Desktop.

Introduction

Design Patterns that will be covered in this article:

  • Strategy

Strategy

This design pattern defines a family of interchangeable objects that can be set or switched at runtime. Also, Strategy is categorized under Behavioral patterns because the Strategy pattern is ultimately about 1 object using another to do something.

This pattern has 3 parts in-total:

  • The object using a strategy (typically, a view controller in an iOS app)
  • The Strategy Protocol
    • This protocol defines methods that every strategy must implement
  • The strategies are objects that conform to the Strategy Protocol

When Should You Use It?

  1. Use the strategy pattern when you have 2 or more different interchangeable behaviors
  2. Unlike Delegation, the strategy pattern defines a family of objects
  3. Strategies are intended to be easily changeable at runtime whereas Delegation are often fixed at runtime

Code

AnimeViewController.swift

Screen Shot 2022-03-23 at 7.42.29 PM.png

AnimeDetailViewController.swift

Screen Shot 2022-03-23 at 7.43.10 PM.png

AttackOnTitansStrategy.swift

Screen Shot 2022-03-23 at 7.43.55 PM.png

SwordArtOnlineStrategy.swift

Screen Shot 2022-03-23 at 7.44.38 PM.png

AnimeView.swift

Screen Shot 2022-03-23 at 7.44.59 PM.png

AnimeDetailView.swift

Screen Shot 2022-03-23 at 7.45.34 PM.png

Main.storyboard

Screen Shot 2022-03-23 at 7.46.36 PM.png

Finished Project

Screen Shot 2022-03-23 at 7.49.55 PM.png Screen Shot 2022-03-23 at 7.50.10 PM.png

What Should You be Careful About?

  • Be careful about pre-optimizing and overusing this pattern.
  • If a behavior won't ever change, it's perfectly okay to code it in a controller / object.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment