Skip to content

Instantly share code, notes, and snippets.

@Nirajpaul2
Last active December 1, 2024 09:10
Show Gist options
  • Select an option

  • Save Nirajpaul2/66d1261e2f70ade29c160b006bb789f9 to your computer and use it in GitHub Desktop.

Select an option

Save Nirajpaul2/66d1261e2f70ade29c160b006bb789f9 to your computer and use it in GitHub Desktop.
family of algorithms
//************************************** family of algorithms ******************************
A family of algorithms refers to a set of related algorithms that solve the same type of problem but use different approaches.
For example:
Sorting: Bubble Sort, Quick Sort, Merge Sort.
Payment processing: Credit Card, Debit Card, Net Banking.
Compression: ZIP, RAR, GZIP.
These algorithms share a common purpose or goal but differ in their implementation details.
//************************************** Encapsulates Each One in a Separate Class ******************************
//Instead of implementing multiple algorithms in one class using conditional logic (if-else or switch),
// the Strategy Pattern separates each algorithm into its own class.
//Each class implements a common interface or protocol, ensuring all algorithms can be used interchangeably.
//For example:
protocol SortingStrategy {
func sort(_ array: inout [Int])
}
class BubbleSort: SortingStrategy {
func sort(_ array: inout [Int]) { /* Bubble sort logic */ }
}
class QuickSort: SortingStrategy {
func sort(_ array: inout [Int]) { /* Quick sort logic */ }
}
//************************************** Makes Them Interchangeable ******************************
//Makes Them Interchangeable
Since all algorithms adhere to a common interface or protocol, you can use them interchangeably at runtime.
This means you can easily switch between algorithms without changing the client code.
For example:
let context = SortingContext(strategy: BubbleSort())
context.sortArray(&array) // Uses Bubble Sort
context.setStrategy(QuickSort())
context.sortArray(&array) // Switches to Quick Sort
Interchangeability enables:
Dynamic behavior selection: You can choose an algorithm at runtime based on the situation or user input.
Extensibility: You can add new algorithms without modifying existing code, following the Open/Closed Principle.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment