All guides
Intermediate-AdvancedSelf-pacedFree GuideSection 7/33

Design patterns fondamentaux

Learn to build and check a web application with development tools and AI assistants. Practise design, coding and validation.

The full lessons for this course are currently available in French. Use the section menu to navigate the French course.

💡

Free content, available without an account. Tools and models change: use the current model guide to check their versions. Models and sources

Section 13.2.2 : Design patterns fondamentaux

🎯 Objectif pédagogique

Découvrir les design patterns les plus courants et comprendre quand les appliquer. Ces patterns sont des solutions éprouvées à des problèmes récurrents en conception logicielle.


Qu'est-ce qu'un design pattern ?

Un design pattern est une solution réutilisable à un problème courant. Ce sont des schémas de pensée qui guident l'organisation du code, décrits dans le livre « Design Patterns » de la Gang of Four (GoF) en 1994.

Le pattern Iterator

Ruby l'intègre nativement grâce aux blocs et Enumerable :

class Playlist
  include Enumerable

  def initialize
    @chansons = []
  end

  def ajouter(chanson)
    @chansons << chanson
  end

  def each(&block)
    @chansons.each(&block)
  end
end

playlist = Playlist.new
playlist.ajouter('Bohemian Rhapsody')
playlist.ajouter('Imagine')
playlist.map(&:upcase)
playlist.count

Le pattern Strategy

Changer le comportement via un lambda ou bloc :

class Trieur
  def initialize(strategie = nil)
    @strategie = strategie || ->(a, b) { a <=> b }
  end

  def trier(collection)
    collection.sort(&@strategie)
  end
end

produits = [
  { nom: 'MacBook', prix: 2399 },
  { nom: 'iPad', prix: 899 },
  { nom: 'iPhone', prix: 1199 }
]

par_prix = ->(a, b) { a[:prix] <=> b[:prix] }
par_nom = ->(a, b) { a[:nom] <=> b[:nom] }

Trieur.new(par_prix).trier(produits)
Trieur.new(par_nom).trier(produits)

Le pattern Observer

Notifier des abonnés quand un événement se produit — Rails l'utilise avec les callbacks :

module Observable
  def self.included(base)
    base.instance_variable_set(:@observers, [])
    base.extend(ClassMethods)
  end

  module ClassMethods
    def add_observer(observer)
      @observers << observer
    end

    def observers
      @observers
    end
  end

  def notify_observers(event, data = {})
    self.class.observers.each do |obs|
      obs.update(event, data) if obs.respond_to?(:update)
    end
  end
end

Le pattern Template Method

Définir le squelette d'un algorithme dans le parent, laisser les sous-classes redéfinir certaines étapes :

class DataExporter
  def export(data)
    header = generate_header
    body = generate_body(data)
    footer = generate_footer
    "#{header}\n#{body}\n#{footer}"
  end

  private

  def generate_header
    raise NotImplementedError
  end

  def generate_body(data)
    raise NotImplementedError
  end

  def generate_footer
    '--- Fin ---'
  end
end

class CSVExporter < DataExporter
  def generate_header
    'nom,email,age'
  end

  def generate_body(data)
    data.map { |row| row.values.join(',') }.join("\n")
  end
end
Loading diagram…
Quick Check

Quel pattern Rails utilise-t-il comme architecture principale ?

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

Your progress

Progress is self-reported and stored in your browser. The final completion record is not a qualification or an independent assessment.

View progress and completion record

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

One practical AI workflow in your inbox

Methods, resources and new exercises. Free, unsubscribe at any time.