Intro to Design Patterns
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 70 of 91.
Design patterns are proven solutions to common problems that developers encounter repeatedly when building software. Rather than reinventing the wheel each time, you can apply these established templates to solve similar challenges in your own code.
Think of design patterns as recipes. Just as a chef follows a recipe to create a dish that's been perfected over time, developers use design patterns to structure their code in ways that have been tested and refined by countless programmers before them.
Design patterns are typically grouped into three categories:
| Category | Purpose | Examples |
|---|---|---|
| Creational | How objects are created | Singleton, Factory |
| Structural | How objects are composed | Adapter, Decorator |
| Behavioral | How objects communicate | Observer, Strategy |
You've actually been using patterns throughout this course without realizing it. When you created abstract classes with methods that child classes must implement, you were applying a form of the Template Method pattern. When you used interfaces to define contracts, you were setting up for the Strategy pattern.
Learning design patterns gives you a shared vocabulary with other developers. Instead of explaining a complex structure in detail, you can simply say "I used the Factory pattern here" and experienced developers will immediately understand your approach. In the following lessons, we'll implement several essential patterns in PHP.
Challenge
EasyLet's build a simple message formatting system that demonstrates how design patterns help organize code. You'll identify which pattern category each component belongs to and see how different parts of a system work together.
You'll organize your code across three files:
MessageFormatter.php— Create an interface calledMessageFormatterthat defines a contract for formatting messages. It should have a single methodformat(string $message): string. This represents the behavioral category — it defines how objects communicate and process data.Formatters.php— Include the MessageFormatter file and create two classes that implement the interface:UppercaseFormatter— Itsformat()method returns the message converted to uppercaseBracketFormatter— Itsformat()method wraps the message in square brackets like[message]
main.php— Include the Formatters file. You'll receive two inputs: a message string and a formatter type ("upper"or"bracket").Create a function called
processMessagethat accepts aMessageFormatterand a message string, then returns the formatted result. This function doesn't need to know which specific formatter it receives — it just callsformat()on whatever object is passed in.Based on the formatter type input, create the appropriate formatter object. Pass it to your
processMessagefunction along with the message, and print the result.On a new line, print which pattern category this structure represents. Since we're defining interchangeable behaviors through an interface, print:
Pattern category: Behavioral
This challenge shows how interfaces let you swap implementations without changing the code that uses them — a foundation for patterns like Strategy that you'll explore in upcoming lessons.
Cheat sheet
Design patterns are proven solutions to common programming problems that provide templates for structuring code effectively.
Design patterns are grouped into three 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 provide a shared vocabulary among developers, making it easier to communicate complex architectural decisions.
Try it yourself
<?php
require_once 'Formatters.php';
// Read input
$message = trim(fgets(STDIN));
$formatterType = trim(fgets(STDIN));
// TODO: Create a function called processMessage that accepts a MessageFormatter
// and a message string, then returns the formatted result
// TODO: Based on $formatterType ("upper" or "bracket"), create the appropriate formatter
// TODO: Call processMessage with the formatter and message, then print the result
// TODO: Print the pattern category on a new line
// Format: "Pattern category: Behavioral"
?>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 FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern