Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions chunks/structural_global_object.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
file: structural/global_object.py
chunk: structural_global_object.md
---

```python
"""
Global Object Pattern Example

This pattern exposes a globally shared object (singleton-like) through module-level
declaration. It provides centralized access to application-wide state or configuration
without enforcing a strict Singleton structure.

Used for: shared config, feature toggles, session state, or dependency registry.

Pattern Type: Structural
"""

# config.py
class AppConfig:
"""
AppConfig is a shared global object used to store application settings.
"""
def __init__(self):
self.environment = "development"
self.debug_mode = False
self.api_key = None

# This global instance is what other modules will import
global_config = AppConfig()

# service.py
def initialize_service():
from config import global_config
print(f"[Service] Running in {global_config.environment} mode.")
if global_config.debug_mode:
print("[Service] Debug mode is enabled.")

def update_api_key(new_key: str):
from config import global_config
global_config.api_key = new_key
print(f"[Service] Updated API key to: {global_config.api_key}")

# main.py
def main():
from config import global_config
import service

# Configure shared state
global_config.environment = "production"
global_config.debug_mode = True

# Service modules use the shared object
service.initialize_service()
service.update_api_key("SECRET-123")

# Show that the global object retains the update
print(f"[Main] Confirmed API key: {global_config.api_key}")

if __name__ == "__main__":
main()

```

## Summary
This code demonstrates the Global Object Pattern, showcasing a shared configuration object accessible across modules.

## Docstrings
- AppConfig is a shared global object used to store application settings.
- initialize_service initializes the service and prints the current environment mode.
- update_api_key updates the API key in the global configuration object.

1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@
- [Structural Decorator](structural_decorator.md)
- [Structural Facade](structural_facade.md)
- [Structural Flyweight](structural_flyweight.md)
- [Structural Global Object](structural_global_object.md)
- [Structural Proxy](structural_proxy.md)
50 changes: 50 additions & 0 deletions docs/structural_global_object.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# The Global Object Pattern (Structural)

## Intent

The global object pattern is a design pattern that exposes a globally shared object through module-level declaration, providing centralized access to application-wide state or configuration without enforcing a strict Singleton structure. It's often used for sharing config data across the app like environment settings, debug mode status, API keys etc.

## Problem It Solves

The problem this pattern solves is related to managing shared global state in large applications where it can be difficult to manage and maintain due to its complexity. This pattern provides a centralized place to store these configurations that can be accessed from anywhere in the application without having to pass them around as function parameters or through class constructors.

## When to Use It

This pattern is ideal when you have shared configuration data across your app, such as environment settings (production vs development), debug mode status, API keys etc.

## When NOT to Use It

It's not recommended for small applications where the scope of the application is limited and there are few shared configurations. Also, it can lead to tight coupling in large systems as it makes the code harder to understand and maintain.

## How It Works

The global object pattern works by declaring a shared object at the module level (usually in its own file). This object can be accessed from anywhere within your application without having to pass it around as function parameters or through class constructors. The shared state is typically initialized once when the module is loaded and remains unchanged throughout the execution of the program.

## Real-World Analogy

Imagine a global dictionary in Python that stores all the configuration settings for an app. You can think of this pattern as similar to how a dictionary (or map) might be used in other programming languages, where you have keys and values that are accessible from anywhere within your program.

## Simplified Example

Here's a simplified example:

```python
# config.py
class AppConfig:
def __init__(self):
self.environment = "development"
self.debug_mode = False
self.api_key = None

global_config = AppConfig() # This is the shared object

# service.py
def initialize_service():
from config import global_config
print(f"[Service] Running in {global_config.environment} mode.")
if global<|begin▁of▁sentence|>:
```

## See Also

You can find the full implementation of this pattern [here](https://github.com/taggedzi/python-design-pattern-rag/blob/main/patterns/structural/global_object.py).
55 changes: 55 additions & 0 deletions patterns/structural/global_object.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
Global Object Pattern Example

This pattern exposes a globally shared object (singleton-like) through module-level
declaration. It provides centralized access to application-wide state or configuration
without enforcing a strict Singleton structure.

Used for: shared config, feature toggles, session state, or dependency registry.

Pattern Type: Structural
"""

# config.py
class AppConfig:
"""
AppConfig is a shared global object used to store application settings.
"""
def __init__(self):
self.environment = "development"
self.debug_mode = False
self.api_key = None

# This global instance is what other modules will import
global_config = AppConfig()

# service.py
def initialize_service():
from config import global_config
print(f"[Service] Running in {global_config.environment} mode.")
if global_config.debug_mode:
print("[Service] Debug mode is enabled.")

def update_api_key(new_key: str):
from config import global_config
global_config.api_key = new_key
print(f"[Service] Updated API key to: {global_config.api_key}")

# main.py
def main():
from config import global_config
import service

# Configure shared state
global_config.environment = "production"
global_config.debug_mode = True

# Service modules use the shared object
service.initialize_service()
service.update_api_key("SECRET-123")

# Show that the global object retains the update
print(f"[Main] Confirmed API key: {global_config.api_key}")

if __name__ == "__main__":
main()
6 changes: 6 additions & 0 deletions summary_index.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@
"pattern": "",
"summary": "Implementation of the Flyweight Design Pattern in Python to minimize memory usage by sharing common state among similar objects."
},
{
"file": "structural/global_object.py",
"chunk": "structural_global_object.md",
"pattern": "",
"summary": "This code demonstrates the Global Object Pattern, showcasing a shared configuration object accessible across modules."
},
{
"file": "structural/proxy.py",
"chunk": "structural_proxy.md",
Expand Down