Programming principles and design · Lesson 37 of 60 · Concept lesson · Optional
Design patterns
A design pattern is a named, reusable solution to a problem that keeps coming up.
Examples are the observer, where listeners are told when something changes, and the factory, which creates objects for you.
Patterns give a team shared words, but they should solve a real problem, not decorate the code.
Picture it
Code example
const listeners = [];
function subscribe(listener) {
listeners.push(listener);
}
function publish(message) {
for (const listener of listeners) listener(message);
}
subscribe(message => console.log("A got " + message));
subscribe(message => console.log("B got " + message));
publish("hi");Output:
A got hi B got hi
Both listeners are told when the message is published.
listeners = []
def subscribe(listener):
listeners.append(listener)
def publish(message):
for listener in listeners:
listener(message)
subscribe(lambda message: print("A got " + message))
subscribe(lambda message: print("B got " + message))
publish("hi")Output:
A got hi B got hi
Both listeners are told when the message is published.
Check yourself
Pick an answer for each question. You can retry as many times as you like.
Loading the questions…