Intro to Design Patterns
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 51 of 70.
Design patterns are proven solutions to common problems that developers encounter repeatedly when building software. Rather than reinventing the wheel each time, patterns give us a shared vocabulary and tested approaches for structuring code.
Think of design patterns as blueprints. They don't give you exact code to copy, but they describe how to organize classes and objects to solve specific challenges. When someone mentions "use the Factory pattern here," experienced developers immediately understand the general structure being proposed.
Design patterns fall into three main categories:
| Category | Purpose | Examples |
|---|---|---|
| Creational | How objects are created | Singleton, Factory |
| Structural | How objects are composed | Adapter, Decorator |
| Behavioral | How objects communicate | Observer, Strategy |
The patterns we'll explore build directly on OOP concepts you've already learned - interfaces, inheritance, polymorphism, and composition. Each pattern leverages these fundamentals in specific ways to achieve flexibility, maintainability, or reusability.
In the upcoming lessons, you'll implement several essential patterns starting with Singleton, Factory, Observer, and Strategy. Understanding these patterns will help you recognize common solutions in existing codebases and make better architectural decisions in your own projects.
Challenge
EasyLet's build a simple pattern catalog system that organizes design pattern information across multiple files. This will help you understand how patterns are categorized while practicing good code organization.
You'll create three files to separate different responsibilities:
Pattern.cs: Define aPatternclass in thePatternsnamespace that represents a single design pattern. Each pattern should have aName,Category(Creational, Structural, or Behavioral), and aDescription. Include a methodGetSummary()that returns a formatted string:[{Category}] {Name}: {Description}PatternCatalog.cs: Create aPatternCatalogclass in thePatternsnamespace that manages a collection of patterns. Your catalog should be able to add patterns and have a methodGetPatternsByCategory(string category)that returns a list of all patterns matching that category. Also include aGetAllSummaries()method that returns a list of summary strings for all patterns in the catalog.Program.cs: Bring everything together by creating a catalog and populating it with patterns based on input. Then display patterns filtered by category.
You will receive the following inputs:
- Number of patterns to add
- For each pattern: three lines containing name, category, and description
- A category to filter by
After adding all patterns to your catalog, print the summaries of patterns that match the filter category, one per line. If no patterns match, print No patterns found.
For example, if the inputs are:
3
Singleton
Creational
Ensures only one instance exists
Observer
Behavioral
Notifies dependents of state changes
Factory
Creational
Creates objects without specifying exact class
CreationalThe output should be:
[Creational] Singleton: Ensures only one instance exists
[Creational] Factory: Creates objects without specifying exact classThis challenge demonstrates how organizing related classes into separate files keeps your codebase clean and maintainable - a principle that becomes even more important as you implement actual design patterns in upcoming lessons!
Cheat sheet
Design patterns are proven solutions to common problems in software development. They provide blueprints for organizing classes and objects rather than exact code to copy.
Design patterns fall into three main categories:
| Category | Purpose | Examples |
|---|---|---|
| Creational | How objects are created | Singleton, Factory |
| Structural | How objects are composed | Adapter, Decorator |
| Behavioral | How objects communicate | Observer, Strategy |
Design patterns build on OOP concepts like interfaces, inheritance, polymorphism, and composition to achieve flexibility, maintainability, and reusability.
Try it yourself
using System;
using System.Collections.Generic;
using Patterns;
class Program
{
public static void Main(string[] args)
{
// Read the number of patterns
int n = Convert.ToInt32(Console.ReadLine());
// Create a new PatternCatalog
PatternCatalog catalog = new PatternCatalog();
// TODO: Read each pattern's details (name, category, description)
// and add them to the catalog
for (int i = 0; i < n; i++)
{
string name = Console.ReadLine();
string category = Console.ReadLine();
string description = Console.ReadLine();
// TODO: Create a Pattern and add it to the catalog
}
// Read the category to filter by
string filterCategory = Console.ReadLine();
// TODO: Get patterns by the filter category
// and print their summaries
// If no patterns match, print "No patterns found"
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List10Design Patterns Part 1
Intro to Design PatternsThread-Safe SingletonFactory PatternObserver Pattern (Events)Strategy Pattern2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator