Design Patterns Introduction
- 53Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
- spaceFlip card
- KI knew it
- DI didn't know it
- ←Previous card
- →Next card
What are design patterns?
Ways of solving similar problems in similar ways—accepted standard solutions to common software development issues.
Or swipe the card
53 cards
What are design patterns?
Ways of solving similar problems in similar ways—accepted standard solutions to common software development issues.
What benefits do design patterns provide?
Scalability, testability, separation of concerns, better architecture and maintainability, standard terminology, and best practices.
Who are the Gang of Four?
A group of four software development architects who wrote the foundational book on design patterns, describing best ways to solve common problems.
What are the three types of design patterns?
Creational, Structural, and Behavioral.
What is the purpose of creational design patterns?
To handle how objects or components are created, providing flexibility and efficiency in instantiation based on requirements.
What is the purpose of structural design patterns?
To structure classes or components to achieve objectives like testability and scalability, focusing on how components are composed.
What is the purpose of behavioral design patterns?
To manage how components behave and interact with each other, including communication and responsibility.
What problem does the Singleton pattern solve?
It ensures a class has only one instance and provides a global point of access to that instance, useful for shared resources like network communicators, databases, or loggers.
What are the disadvantages of the Singleton pattern?
Breaks single responsibility principle, causes testability issues (tight coupling, cannot mock easily), and state persists for the application lifetime.
How is a naive Singleton implemented in Python?
Define a metaclass with
__call__that checkscls not in cls._instances, creates instance viasuper().__call__(*args, **kwargs), stores it, and returnscls._instances[cls].Why does a naive Singleton fail in multithreaded environments?
Multiple threads can simultaneously check
if cls not in cls._instancesbefore any instance is created, leading to multiple instances being created.How do you make a Singleton thread-safe?
Add a lock (e.g.,
_lock = threading.Lock()) and within__call__, usewith self._lock:around the instance creation block.What problem does the Factory Method pattern solve?
It separates object creation from its usage, allowing dynamic switching between different implementations and easy code changes without tight coupling.
How does Factory Method achieve separation of concerns?
The client uses an object via a common interface without knowing its concrete type; a separate factory class creates the appropriate object based on context.
In the currency example, how is Factory Method implemented?
An abstract
CurrencyFactoryclass withcurrency_factory(country)method. Concrete factories likeFiatCurrencyFactoryandVirtualCurrencyFactoryoverride it to return specific currencies (USD, EUR, JPY for fiat; Bitcoin, Ethereum, Dogecoin for virtual).What is Abstract Factory pattern?
A factory that creates factories—one level of abstraction above Factory Method. It provides a way to access functionality without caring about the implementation of the factory itself.
In the restaurant example, how is Abstract Factory implemented?
An abstract
Restaurantclass withmake_food()andmake_drink()methods. ConcreteFrenchRestaurantandAmericanRestaurantimplement them. ARestaurantFactory(abstract factory) returns the appropriate restaurant based onFoodType(French/American). The clientdine_atuses the restaurant without knowing which concrete restaurant it is.What problem does the Builder pattern solve?
It allows flexible initialization of objects with many parameters, avoiding telescoping constructors and making object construction easy to read and use.
What are the two implementations of Builder in Python shown?
- Classic Builder: separate class with methods to set parameters and a
build()method. 2) Simplified: using named parameters with default values in the constructor.
- Classic Builder: separate class with methods to set parameters and a
In the classic Builder example with NetworkService, how is the object built?
NetworkServiceBuilderhasadd_target_url,add_authorization,add_cachingmethods that call_service.add(key, value).build()returns the_serviceinstance after resetting it.What problem does the Prototype pattern solve?
It allows copying existing objects without depending on their classes, providing a way to create duplicates of complex objects, including their state.
How is Prototype implemented in Python?
Using the
copymodule:copy.copy(obj)for shallow copy orcopy.deepcopy(obj)for deep copy. The object must provide the copy functionality if needed.In the shape/abstract art example, how is Prototype demonstrated?
art2 = copy.copy(art1)creates a copy of theAbstractArtobject. Both art1 and art2 have the same background color and shapes list; drawing them produces identical output.What problem does the Adapter pattern solve?
It converts an interface of one class into another interface that the client expects, allowing incompatible classes to work together without modifying the third-party or legacy code.
In the adapter example with data types, how is the adapter created?
DisplayDataAdapterinherits fromStoreDatabaseData(client's class) and usesDisplayData(third-party) internally. It overridesstore_datato convertDatabaseDataType(position, amount) toDisplayDataType(index, data) and then calls the third-party'sshow_data.What problem does the Bridge pattern solve?
It avoids an explosion of classes when multiple orthogonal traits (e.g., shape and color) need to be combined, by replacing inheritance with composition.
How is Bridge implemented in the device/remote control example?
An abstract
Deviceclass withvolumeandget_name(). ConcreteRadioandTVimplementget_name(). An abstractRemoteclass withvolume_up()andvolume_down().BasicRemotetakes aDevicein its constructor and operates on it via the bridge.What problem does the Composite pattern solve?
It allows treating individual objects and compositions of objects uniformly, often used when functionality can be represented as a tree structure (e.g., pricing parts of a computer).
In the composite example with equipment, how is the price calculated?
An
Equipmentclass has name and price. ACompositeclass (e.g.,Memory,Computer) holds a list of items and itspriceproperty returnssum(x.price for x in self.items). Adding items creates a tree; callingcomputer.pricerecursively calculates the total.What problem does the Decorator pattern solve?
It allows adding new behavior to an object dynamically without altering its code, useful when extending third-party classes or when behavior needs to be added in flexible combinations.
In the coffee machine example, how are behaviors added?
BasicCoffeeMachineimplementsmake_small_coffee()andmake_large_coffee().EnhancedCoffeeMachinewraps aBasicCoffeeMachine, overridesmake_large_coffeeto print a different message, and addsmake_milk_coffee()which callsbasic_machine.make_small_coffee()then prints 'adding milk'.What problem does the Facade pattern solve?
It provides a simplified interface to a complex subsystem, reducing client complexity and hiding management details.
In the user repository example, how does the facade work?
ComplexSystemStorehandles caching and committing data to a file.UserRepository(the facade) creates aComplexSystemStorefor preferences and exposessave(user)andfind_first()methods that internally use the store. The client only interacts withUserRepository.What problem does the Flyweight pattern solve?
It reduces memory and processing footprint by sharing common parts of many objects (intrinsic state) while keeping unique parts (extrinsic state) per object.
In the flyweight example with fighters, how is sharing achieved?
A
FighterFactorystores only oneFighterper rank (Private, Sergeant, Major).Army.spawn_fighter(rank)uses the factory to get the flyweight fighter; all soldiers of the same rank share the same instance. Intrinsic state: rank; extrinsic: position (not stored in this example).What problem does the Proxy pattern solve?
It controls access to an object by providing a surrogate that manages the object's life cycle, adds caching, sequencing, or authorization, while keeping the same interface as the real object.
In the proxy example with an image, how is caching implemented?
RealImageloads an image from disk.ProxyImagehas the same interface, stores_real_imageinitially None. Ondisplay(), if_real_imageis None, it createsRealImage(from disk) and then calls_real_image.display(). Subsequent calls skip loading (from cache).What problem does the Chain of Responsibility pattern solve?
It allows multiple handlers to process a request, each with the option to pass it to the next handler, enabling flexible processing pipelines.
In the HTTP header example, how is the chain built?
An abstract
HandlerChainwithadd_header(input_header)method. Concrete handlersAuthenticationHeader,ContentTypeHeader,BodyPayloadHeaderimplementadd_headerby appending their header/body and callingself.do_next(input_header). They are linked vianext_header; the chain starts from authentication, then content type, then body.What problem does the Command pattern solve?
It decouples the sender of a request from its execution by encapsulating the request as an object, allowing parameterization, queuing, and logging of requests.
In the order processing example, how are commands used?
Commandis abstract withexecute().OrderAddCommandandOrderPayCommandimplementexecute().CommandProcessorstores commands in a queue;process_commands()iterates andexecute()each, then resets the queue.What problem does the Interpreter pattern solve?
It defines a grammar for a language and provides an interpreter to evaluate sentences in that language, useful for parsing and processing expressions.
In the algebraic expression example, how is an expression interpreted?
Tokens are parsed into an expression tree.
Number(terminal) returns its value.Add,Subtract,Multiply,Divide(nonterminal) interpret left and right recursively and apply the operation. The final result is obtained by callinginterpret()on the root of the tree.What are the two core methods of an iterator?
has_next()returning a boolean, andnext()returning the next element.In the iterator example with words, how are custom iterators created?
AlphabeticalOrderIteratortakes a list of words and a reverse flag. It stores sorted words and position.next()returns current word then increments/decrements position.has_next()checks if position is within bounds.WordsCollectionprovidesget_iterator()andget_reverse_iterator()returning the appropriate iterator.What problem does the Mediator pattern solve?
It centralizes communication between components to reduce dependencies; components talk to a mediator instead of directly to each other.
In the chat group example, how does the mediator work?
Mediatorhas a list of users andsend_message(msg, user)that iterates over all users except the sender and callsuser.receive(msg).ChatUserhas a reference to the mediator; itssend()callsmediator.send_message(). Adding a user sets the mediator viaset_mediator().What problem does the Memento pattern solve?
It allows saving and restoring an object's state without exposing its implementation details, enabling undo/redo functionality.
In the memento example, what are the three components and their roles?
Memento: stores state (a string).Originator: has current state,create_memento()returns a new memento,restore(memento)sets state from memento.Caretaker: holds a list of mementos,save_state()adds a memento,restore(index)returns the memento at that index.What problem does the Observer pattern solve?
It defines a subscription mechanism to notify multiple objects about events that occur, avoiding polling and enabling decoupled communication.
In the editor example, how is Observer implemented?
EventManagermaintains a dict of event type to list of listeners.subscribe()andunsubscribe()modify these lists.notify(event_type, file)callsupdate()on each listener.Editoruses anEventManagerfor 'open' and 'save' events.EmailNotificationListenerandLogOpenListenerimplementupdate()to send email or log.What problem does the State pattern solve?
It allows an object to change its behavior when its internal state changes, appearing to change its class. Ideal for implementing state machines.
In the game state example, how are transitions defined?
Gameholds aStateobject.Stateis abstract with methodson_welcome_screen(),on_playing(),on_break(),on_end_game(). Concrete states likeWelcomeScreenStateimplement these methods; only certain transitions are allowed (e.g., welcome -> playing, playing -> break, playing -> end game). Forbidden transitions print a message.

Ask anything
We've read this whole study set, so questions about it get the best answers.