Skip to content

Study Journal 09-11-2023

Published: at 12:00 AM

What I learnt

Random thoughts to checkout

Design Patterns - here’s a table I made to explain:

Pattern NameUse ForExample ForUse AgainstExample AgainstAlternative Pattern
Creational Patterns
SingletonManaging global application stateA logger class that writes to a single log fileWhen you need separate instancesDifferent log files for different modulesPrototype, Factory Method
Factory MethodDelegating object creation logicA database access class that creates connections to different types of databasesSimple object creationInstantiating a simple class that doesn’t require complex logicSimple Constructor
Abstract FactoryCreating families of related objects without specifying their concrete classesUI toolkit that provides widgets for multiple operating systemsNo need for multiple object familiesAn application that only runs on one operating system and doesn’t need different styles of widgetsSimple Constructor, Builder
BuilderCreating complex objects with multiple optional parametersBuilding an SQL query with various optional filters and parametersWhen object creation is straightforwardInstantiating an object with only mandatory fields and no optional settingsSimple Constructor
PrototypeCreating new objects by copying existing onesDuplicating user-configured settings in a complex configuration objectWhen objects are simple to createCreating a new default configuration object that doesn’t require variationSimple Constructor
Structural Patterns
AdapterAllowing classes with incompatible interfaces to work togetherWrapping an old API to match a new interface expected by modern codeWhen you control the interfacesCreating a new system where you define all the interfaces to be compatible from the startNone needed (use direct implementation)
BridgeSeparating an abstraction from its implementation so they can vary independentlyA game engine that can run with different rendering APIs (OpenGL, DirectX)No need for varying abstractionsA script that performs a single, specific task without the need for interchangeable back-end processesNone needed (use direct implementation)
CompositeTreating individual and composite objects uniformlyA graphic editor that handles both individual shapes and groups of shapesNo need to treat objects uniformlyA simple application where objects are always treated individuallyNone needed (use direct implementation)
DecoratorAdding responsibilities to objects dynamically without changing their implementationAdding new encryption layers to a data stream without changing the original data source classWhen subclassing is more appropriateExtending a class hierarchy with new subclass for each specific featureSubclassing
FacadeProviding a simple interface to a complex subsystemA high-level interface for video conversion that hides the complex underlying librariesWhen you need to work with the complexity directlyWhen you need to perform complex operations with fine-grained controlNone needed (work directly with the complex subsystem)
FlyweightSharing fine-grained objects to reduce memory usageReusing character objects in a word processor to save memoryWhen memory usage is not a concernAn application that creates a small number of heavy objects that don’t share stateNone needed (use direct instantiation)
ProxyControlling access to an object, lazy instantiation, or implementing loggingA virtual proxy for a large image that is only loaded into memory when actually neededWhen direct object access is acceptableAccessing a small, in-memory database where proxying would add unnecessary overheadNone needed (use direct access)
Behavioral Patterns
Chain of ResponsibilityPassing requests along a chain of handlers until one handles itEvent propagation in a GUI framework, where an event travels up through a component hierarchy until it’s handledWhen only one handler should be usedProcessing a request that should be handled by a single, specific handlerCommand
CommandEncapsulating a request as an objectUndo/Redo operations in a text editor, where each edit action is a command objectWhen actions are simple and can be executed directlySimple callback functions for button clicks in a simple GUIStrategy
InterpreterDefining a way to evaluate sentences in a languageA formula parser in a spreadsheet application that interprets cell formulasWhen the language is too complex for the patternParsing a full-featured programming language with complex syntax and semanticsParser / Compiler library
IteratorProviding a way to access elements of a collection sequentially without exposing its underlying representationIterating over a collection of objects in an application without exposing the collection’s structureWhen the collection is simple and can be accessed directlyAccessing elements in a fixed array with known dimensionsNone needed (use direct access)
MediatorReducing direct communication between classes to make them less dependent on each otherA chat application where the server acts as a mediator between clientsWhen direct communication is preferred for simplicityA two-player game where players interact directly without a central mediatorNone needed (use direct communication)
MementoCapturing and externalizing an object’s internal state without violating encapsulationSaving the state of a complex object to restore it later, like a snapshot feature in a virtual machineWhen exposing the internal state is not problematicA simple data structure where the state can be easily managed and doesn’t need encapsulationState pattern (if behavior changes are needed)
ObserverAllowing subscribers to be notified of changes in another objectA weather station application that updates multiple displays when the weather data changesWhen changes do not need to be communicated in real-timeLogging information where updates can be checked periodically without instant notificationPolling or Callbacks
StateAllowing an object to change its behavior when its internal state changesA network connection that changes its behavior based on the connection state (connected, disconnected, attempting to connect)When state changes are so simple that a state machine is overkillA light bulb that is either on or off, with a simple toggle switchNone needed (use direct conditionals)
StrategyEncapsulating different algorithms or behaviors to be selected at runtimeDifferent sorting algorithms that can be selected based on the size and type of the dataWhen there is only one algorithm or behaviorA service that always uses the same algorithm because it’s the only one suitable for its purposeNone needed (implement the algorithm directly)
Template MethodDefining the skeleton of an algorithm and letting subclasses redefine certain stepsA data miner that provides a template for parsing, analyzing, and reporting data, but lets subclasses define the parsing logicWhen the algorithm doesn’t vary or when there is little to no common behaviorA simple task that doesn’t require varying steps or can be completed in a single functionStrategy (if different algorithms are needed)
Consider supporting this blog