10 Most Common Questions & Answers About Design Pattern (implemented by PHP)

Introduction

Most of the time for my learning I create simple note. This article is also one of my note for learning design pattern in PHP. To write this article I’ve taken help from a various websites and used natural language processing tools. So, let’s learn together🤓!

Q1: What is the Singleton pattern? Explain its purpose and provide an example of its implementation in PHP.

Ans: The Singleton pattern ensures that a class has only one instance throughout the application and provides a global point of access to it. It is useful when we need to restrict the instantiation of a class to a single object. Here’s an example of implementing the Singleton pattern in PHP:

class Singleton {
   private static $instance;

   private function __construct() {}

   public static function getInstance() {
      if (!self::$instance) {
         self::$instance = new self();
      }
      return self::$instance;
   }
}

Q2: Describe the Factory pattern. How does it promote flexibility and decoupling in object creation? Provide a PHP-based example to illustrate its usage.

Ans: The Factory pattern provides an interface for creating objects without exposing the object instantiation logic to the client. It promotes flexibility by allowing subclasses to decide which class to instantiate based on certain conditions. This decouples the client from the specific classes being created. Here’s a PHP-based example:

interface Vehicle {
   public function drive();
}

class Car implements Vehicle {
   public function drive() {
      echo "Driving a car.";
   }
}

class Bike implements Vehicle {
   public function drive() {
      echo "Riding a bike.";
   }
}

class VehicleFactory {
   public static function createVehicle($type) {
      if ($type === 'car') {
         return new Car();
      } elseif ($type === 'bike') {
         return new Bike();
      }
      return null;
   }
}

Q3: Explain the Abstract Factory pattern. How does it differ from the Factory pattern? Provide a PHP-based example of implementing the Abstract Factory pattern.

Ans: The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It differs from the Factory pattern by abstracting the creation of multiple related objects instead of just a single object. Here’s a PHP-based example of implementing the Abstract Factory pattern:

interface Button {
   public function render();
}

class WindowsButton implements Button {
   public function render() {
      echo "Rendering a Windows button.";
   }
}

class MacButton implements Button {
   public function render() {
      echo "Rendering a Mac button.";
   }
}

interface GUIFactory {
   public function createButton(): Button;
}

class WindowsFactory implements GUIFactory {
   public function createButton(): Button {
      return new WindowsButton();
   }
}

class MacFactory implements GUIFactory {
   public function createButton(): Button {
      return new MacButton();
   }
}

Q4: What is the Adapter pattern? How does it allow incompatible interfaces to work together? Provide a PHP-based example of implementing the Adapter pattern.

Ans: The Adapter pattern allows objects with incompatible interfaces to work together by creating a wrapper class that translates the interface of one class into another interface that the client expects. This allows the objects to collaborate without changing their existing code. Here’s a PHP-based example of implementing the Adapter pattern:

interface MediaPlayer {
   public function play($audioType, $fileName);
}

interface AdvancedMediaPlayer {
   public function playVlc($fileName);
   public function playMp4($fileName);
}

class VlcPlayer implements AdvancedMediaPlayer {
   public function playVlc($fileName) {
      echo "Playing Vlc file: $fileName";
   }

   public function playMp4($fileName) {
      // Do nothing
   }
}

class Mp4Player implements AdvancedMediaPlayer {
   public function playVlc($fileName) {
      // Do nothing
   }

   public function playMp4($fileName) {
      echo "Playing Mp4 file: $fileName";
   }
}

class MediaAdapter implements MediaPlayer {
   private $advancedMediaPlayer;

   public function __construct($audioType) {
      if ($audioType == "vlc") {
         $this->advancedMediaPlayer = new VlcPlayer();
      } else if ($audioType == "mp4") {
         $this->advancedMediaPlayer = new Mp4Player();
      }
   }

   public function play($audioType, $fileName) {
      if ($audioType == "vlc") {
         $this->advancedMediaPlayer->playVlc($fileName);
      } else if ($audioType == "mp4") {
         $this->advancedMediaPlayer->playMp4($fileName);
      }
   }
}

class AudioPlayer implements MediaPlayer {
   private $mediaAdapter;

   public function play($audioType, $fileName) {
      if ($audioType == "mp3") {
         echo "Playing Mp3 file: $fileName";
      } else if ($audioType == "vlc" || $audioType == "mp4") {
         $this->mediaAdapter = new MediaAdapter($audioType);
         $this->mediaAdapter->play($audioType, $fileName);
      } else {
         echo "Invalid media type. Only mp3, vlc, and mp4 formats are supported.";
      }
   }
}

// Usage example
$audioPlayer = new AudioPlayer();

$audioPlayer->play("mp3", "song.mp3"); // Output: Playing Mp3 file: song.mp3
$audioPlayer->play("vlc", "movie.vlc"); // Output: Playing Vlc file:

Q5: Describe the Bridge pattern. How does it facilitate loose coupling between abstractions and implementations? Provide a PHP-based example to demonstrate its usage.

Ans: The Bridge pattern decouples an abstraction from its implementation, allowing them to vary independently. It promotes loose coupling by encapsulating the implementation details within separate classes. Here’s a PHP-based example illustrating the Bridge pattern:

interface Color {
   public function applyColor();
}

class RedColor implements Color {
   public function applyColor() {
      echo "Applying red color.";
   }
}

class BlueColor implements Color {
   public function applyColor() {
      echo "Applying blue color.";
   }
}

abstract class Shape {
   protected $color;

   public function __construct(Color $color) {
      $this->color = $color;
   }

   abstract public function draw();
}

class Square extends Shape {
   public function draw() {
      echo "Drawing a square. ";
      $this->color->applyColor();
   }
}

class Circle extends Shape {
   public function draw() {
      echo "Drawing a circle. ";
      $this->color->applyColor();
   }
}

Q6: What is the Observer pattern? Explain its purpose and how it establishes a one-to-many dependency. Provide a PHP-based example to illustrate the Observer pattern.

Ans: The Observer pattern establishes a one-to-many dependency between objects, where multiple observers (dependents) are notified automatically when the state of a subject (observable) changes. The purpose of this pattern is to ensure consistency between related objects. Here’s a PHP-based example to illustrate the Observer pattern:

interface Subject {
   public function attach(Observer $observer);
   public function detach(Observer $observer);
   public function notify();
}

interface Observer {
   public function update();
}

class ConcreteSubject implements Subject {
   private $observers;
   private $state;

   public function __construct() {
      $this->observers = [];
   }

   public function attach(Observer $observer) {
      $this->observers[] = $observer;
   }

   public function detach(Observer $observer) {
      $index = array_search($observer, $this->observers);
      if ($index !== false) {
         array_splice($this->observers, $index, 1);
      }
   }

   public function notify() {
      foreach ($this->observers as $observer) {
         $observer->update();
      }
   }

   public function setState($state) {
      $this->state = $state;
      $this->notify();
   }

   public function getState() {
      return $this->state;
   }
}

class ConcreteObserver implements Observer {
   private $subject;

   public function __construct(Subject $subject) {
      $this->subject = $subject;
      $this->subject->attach($this);
   }

   public function update() {
      echo "Observer updated. New state: " . $this->subject->getState();
   }
}

Q7: Describe the Strategy pattern. How does it enable dynamic algorithm selection? Provide a PHP-based example to demonstrate the implementation of the Strategy pattern.

Ans: The Strategy pattern enables dynamic algorithm selection by encapsulating different algorithms within interchangeable objects. It allows clients to select different strategies at runtime without modifying their core logic. Here’s a PHP-based example illustrating the Strategy pattern:

interface SortingStrategy {
   public function sort(array $data);
}

class BubbleSort implements SortingStrategy {
   public function sort(array $data) {
      echo "Sorting using bubble sort.";
      // Bubble sort implementation
   }
}

class QuickSort implements SortingStrategy {
   public function sort(array $

Q8: Explain the Composite pattern. How does it represent part-whole hierarchies? Provide a PHP-based example to illustrate the Composite pattern.

Ans: The Composite pattern represents part-whole hierarchies by allowing clients to treat individual objects and compositions of objects uniformly. It enables the creation of nested structures where a component can be either an individual object or a collection of objects. Here’s a PHP-based example demonstrating the Composite pattern:

interface Component {
   public function operation();
}

class Leaf implements Component {
   public function operation() {
      echo "Leaf operation.";
   }
}

class Composite implements Component {
   private $components = [];

   public function add(Component $component) {
      $this->components[] = $component;
   }

   public function remove(Component $component) {
      $index = array_search($component, $this->components);
      if ($index !== false) {
         array_splice($this->components, $index, 1);
      }
   }

   public function operation() {
      echo "Composite operation.";
      foreach ($this->components as $component) {
         $component->operation();
      }
   }
}

Q9: What is the Decorator pattern? How does it allow for adding behavior to an object dynamically? Provide a PHP-based example of implementing the Decorator pattern.

Ans: The Decorator pattern allows behavior to be added to an object dynamically by wrapping the original object with one or more decorator classes. It provides an alternative to subclassing for extending functionality. Here’s a PHP-based example of implementing the Decorator pattern:

interface Pizza {
   public function getDescription();
   public function getCost();
}

class PlainPizza implements Pizza {
   public function getDescription() {
      return "Plain pizza";
   }

   public function getCost() {
      return 10.0;
   }
}

abstract class PizzaDecorator implements Pizza {
   protected $pizza;

   public function __construct(Pizza $pizza) {
      $this->pizza = $pizza;
   }

   public function getDescription() {
      return $this->pizza->getDescription();
   }

   public function getCost() {
      return $this->pizza->getCost();
   }
}

class CheeseDecorator extends PizzaDecorator {
   public function getDescription() {
      return parent::getDescription() . ", with extra cheese";
   }

   public function getCost() {
      return parent::getCost() + 2.0;
   }
}

class MushroomDecorator extends PizzaDecorator {
   public function getDescription() {
      return parent::getDescription() . ", with mushrooms";
   }

   public function getCost() {
      return parent::getCost() + 1.5;
   }
}

Q10: Describe the Template Method pattern. How does it define the skeleton of an algorithm while allowing subclasses to provide certain implementations? Provide a PHP-based example to illustrate the Template Method pattern.

Ans: The Template Method pattern defines the skeleton of an algorithm in a base class while allowing subclasses to provide certain implementations of steps within that algorithm. It encapsulates the common behavior in the base class while allowing subclasses to customize specific steps. Here’s a PHP-based example to illustrate the Template Method pattern:

abstract class Game {
   abstract protected function initialize();
   abstract protected function startPlay();
   abstract protected function endPlay();

   public final function play() {
      $this->initialize();
      $this->startPlay();
      $this->endPlay();
   }
}

class Football extends Game {
   protected function initialize() {
      echo "Football game initialized.";
   }

   protected function startPlay() {
      echo "Football game started.";
   }

   protected function endPlay() {
      echo "Football game ended.";
   }

If you get any mistake or if you have any kind of feedback please feel free to comment.

Thank you ❤️

Leave a Reply

Your email address will not be published. Required fields are marked *