Observer
Évènements (C#)
public class Truc
{
public event Action<int> ContentUpdated;
public void DoThing()
{
ContentUpdated?.Invoke(123);
}
}
var obj = new Truc();
obj.ContentUpdated += val => Console.WriteLine(val);
Event listeners (JS, PHP, ...)
document.getElementById("myButton").addEventListener("click", function() {
alert("Clicked!");
});
Strategy
Pointeurs de fonctions (C, C++) / fonctions déléguées (C#) / fonctions de première classe (JS, PHP) / fonctions lambda (Java)
int Carre(int x) => x * x;
int Double(int x) => x + x;
Func<int, int> operation = Carre;
int result = operation(123);
function carre(x) { return x * x; }
function double(x) { return x + x; }
const operation = carre;
const result = operation(123);
Iterator
foreach (C#, PHP) / for..of (JS) / for..: (Java) / for (Python)
var squares = new [] { 1, 4, 8, 2 }.Select(y => Carre(y));
foreach (var x in squares) { ... }
squares = (carre(y) for y in [1, 4, 8, 2])
for x in squares: ...
Bridge
Interfaces (C#, Java, C++)
public interface ITruc { int Fonction(); }
public class Concrete1 : ITruc { public int Fonction() => 5; }
public class Concrete2 : ITruc { public int Fonction() => 123; }
ITruc implementation = new Concrete1();
Visitor (double dispatch)
Pattern matching (C#, Scala)
public int Visit(Node node) => node switch
{
IntNode(var value) => value,
AddNode(var x, var y) => Visit(x) + Visit(y),
MulNode(var x, var y) => Visit(x) * Visit(y)
}
Builder
Valeurs par défaut de paramètres (C#, Python, C++, JS, VB)
public class Car
{
public Car(int wheels = 4, int doors = 5, TransmissionType transmission = Traction, ...)
{
...
}
}