1. Home
  2. Explore
  3. Computer Science
  4. Design Patterns Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Design Patterns Introduction

  • 53Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Design Patterns Intro
  • spaceFlip card
  • KI knew it
  • DI didn't know it
  • ←Previous card
  • →Next card

What are design patterns?

Tap to flipClick to flipspace

Ways of solving similar problems in similar ways—accepted standard solutions to common software development issues.

Or swipe the card

53 cards

  1. What are design patterns?

    Ways of solving similar problems in similar ways—accepted standard solutions to common software development issues.

  2. What benefits do design patterns provide?

    Scalability, testability, separation of concerns, better architecture and maintainability, standard terminology, and best practices.

  3. 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.

  4. What are the three types of design patterns?

    Creational, Structural, and Behavioral.

  5. 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.

  6. 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.

  7. What is the purpose of behavioral design patterns?

    To manage how components behave and interact with each other, including communication and responsibility.

  8. 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.

  9. 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.

  10. How is a naive Singleton implemented in Python?

    Define a metaclass with __call__ that checks cls not in cls._instances, creates instance via super().__call__(*args, **kwargs), stores it, and returns cls._instances[cls].

  11. Why does a naive Singleton fail in multithreaded environments?

    Multiple threads can simultaneously check if cls not in cls._instances before any instance is created, leading to multiple instances being created.

  12. How do you make a Singleton thread-safe?

    Add a lock (e.g., _lock = threading.Lock()) and within __call__, use with self._lock: around the instance creation block.

  13. 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.

  14. 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.

  15. In the currency example, how is Factory Method implemented?

    An abstract CurrencyFactory class with currency_factory(country) method. Concrete factories like FiatCurrencyFactory and VirtualCurrencyFactory override it to return specific currencies (USD, EUR, JPY for fiat; Bitcoin, Ethereum, Dogecoin for virtual).

  16. 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.

  17. In the restaurant example, how is Abstract Factory implemented?

    An abstract Restaurant class with make_food() and make_drink() methods. Concrete FrenchRestaurant and AmericanRestaurant implement them. A RestaurantFactory (abstract factory) returns the appropriate restaurant based on FoodType (French/American). The client dine_at uses the restaurant without knowing which concrete restaurant it is.

  18. 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.

  19. What are the two implementations of Builder in Python shown?

    1. Classic Builder: separate class with methods to set parameters and a build() method. 2) Simplified: using named parameters with default values in the constructor.
  20. In the classic Builder example with NetworkService, how is the object built?

    NetworkServiceBuilder has add_target_url, add_authorization, add_caching methods that call _service.add(key, value). build() returns the _service instance after resetting it.

  21. 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.

  22. How is Prototype implemented in Python?

    Using the copy module: copy.copy(obj) for shallow copy or copy.deepcopy(obj) for deep copy. The object must provide the copy functionality if needed.

  23. In the shape/abstract art example, how is Prototype demonstrated?

    art2 = copy.copy(art1) creates a copy of the AbstractArt object. Both art1 and art2 have the same background color and shapes list; drawing them produces identical output.

  24. 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.

  25. In the adapter example with data types, how is the adapter created?

    DisplayDataAdapter inherits from StoreDatabaseData (client's class) and uses DisplayData (third-party) internally. It overrides store_data to convert DatabaseDataType (position, amount) to DisplayDataType (index, data) and then calls the third-party's show_data.

  26. 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.

  27. How is Bridge implemented in the device/remote control example?

    An abstract Device class with volume and get_name(). Concrete Radio and TV implement get_name(). An abstract Remote class with volume_up() and volume_down(). BasicRemote takes a Device in its constructor and operates on it via the bridge.

  28. 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).

  29. In the composite example with equipment, how is the price calculated?

    An Equipment class has name and price. A Composite class (e.g., Memory, Computer) holds a list of items and its price property returns sum(x.price for x in self.items). Adding items creates a tree; calling computer.price recursively calculates the total.

  30. 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.

  31. In the coffee machine example, how are behaviors added?

    BasicCoffeeMachine implements make_small_coffee() and make_large_coffee(). EnhancedCoffeeMachine wraps a BasicCoffeeMachine, overrides make_large_coffee to print a different message, and adds make_milk_coffee() which calls basic_machine.make_small_coffee() then prints 'adding milk'.

  32. What problem does the Facade pattern solve?

    It provides a simplified interface to a complex subsystem, reducing client complexity and hiding management details.

  33. In the user repository example, how does the facade work?

    ComplexSystemStore handles caching and committing data to a file. UserRepository (the facade) creates a ComplexSystemStore for preferences and exposes save(user) and find_first() methods that internally use the store. The client only interacts with UserRepository.

  34. 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.

  35. In the flyweight example with fighters, how is sharing achieved?

    A FighterFactory stores only one Fighter per 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).

  36. 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.

  37. In the proxy example with an image, how is caching implemented?

    RealImage loads an image from disk. ProxyImage has the same interface, stores _real_image initially None. On display(), if _real_image is None, it creates RealImage (from disk) and then calls _real_image.display(). Subsequent calls skip loading (from cache).

  38. 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.

  39. In the HTTP header example, how is the chain built?

    An abstract HandlerChain with add_header(input_header) method. Concrete handlers AuthenticationHeader, ContentTypeHeader, BodyPayloadHeader implement add_header by appending their header/body and calling self.do_next(input_header). They are linked via next_header; the chain starts from authentication, then content type, then body.

  40. 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.

  41. In the order processing example, how are commands used?

    Command is abstract with execute(). OrderAddCommand and OrderPayCommand implement execute(). CommandProcessor stores commands in a queue; process_commands() iterates and execute() each, then resets the queue.

  42. 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.

  43. 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 calling interpret() on the root of the tree.

  44. What are the two core methods of an iterator?

    has_next() returning a boolean, and next() returning the next element.

  45. In the iterator example with words, how are custom iterators created?

    AlphabeticalOrderIterator takes 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. WordsCollection provides get_iterator() and get_reverse_iterator() returning the appropriate iterator.

  46. 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.

  47. In the chat group example, how does the mediator work?

    Mediator has a list of users and send_message(msg, user) that iterates over all users except the sender and calls user.receive(msg). ChatUser has a reference to the mediator; its send() calls mediator.send_message(). Adding a user sets the mediator via set_mediator().

  48. 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.

  49. 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.

  50. 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.

  51. In the editor example, how is Observer implemented?

    EventManager maintains a dict of event type to list of listeners. subscribe() and unsubscribe() modify these lists. notify(event_type, file) calls update() on each listener. Editor uses an EventManager for 'open' and 'save' events. EmailNotificationListener and LogOpenListener implement update() to send email or log.

  52. 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.

  53. In the game state example, how are transitions defined?

    Game holds a State object. State is abstract with methods on_welcome_screen(), on_playing(), on_break(), on_end_game(). Concrete states like WelcomeScreenState implement these methods; only certain transitions are allowed (e.g., welcome -> playing, playing -> break, playing -> end game). Forbidden transitions print a message.

Card 1 of 53
Card 1 of 53

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent