liveBook · Manning

Singleton pattern

As explained in AI-Powered Developer: Build software with ChatGPT and Copilot

The Singleton Pattern is a software design pattern that restricts a class to one instance and provides a global access point to it.

The Singleton pattern restricts a class to one instance and provides a global access point to that shared object. It suits logging, caching, configuration, and database connection management. section 4.3.3

A practical use is replacing an in-memory repository with database persistence while keeping one shared connection manager. Database settings belong in environment variables rather than source code, and SQLAlchemy supplies the database integration. section 4.3.3 section 4.3.4

Database connection manager

A DatabaseConnection class stores a private instance, exposes get_instance(), and rejects construction after the first instance exists. Its constructor creates a SQLAlchemy engine and session factory from DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT, and DB_NAME. section 4.3.4

Review the implementation before applying it:

  • Keep usernames, passwords, and connection details out of source code; configure them per environment. section 4.3.4
  • Wire the connection manager, repository, service, adapter, and controller in the application entry point so components remain replaceable. section 4.3.4
Listing 4.29 Implementation of a DatabaseConnection
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
 
class DatabaseConnection:
    __instance = None
    @staticmethod
    def get_instance():
        if DatabaseConnection.__instance == None:
            DatabaseConnection()
        return DatabaseConnection.__instance
  
    def __init__(self):
        if DatabaseConnection.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            DatabaseConnection.__instance = self
            self.engine = 
create_engine(f"postgresql://
{os.environ['DB_USERNAME']}:
{os.environ['DB_PASSWORD']}@
{os.environ['DB_HOST']}:
{os.environ['DB_PORT']}/
{os.environ['DB_NAME']}")
            self.Session = sessionmaker(bind=self.engine)
    
    def get_session(self):
        return self.Session()

Inspect the complete Python implementation of the singleton database connection, including instance access, construction protection, engine creation, and session generation. section 4.3.4

How AI-Powered Developer: Build software with ChatGPT and Copilot covers it

How deep it goes
Defines the pattern and implements instance protection, connection creation, session generation, and application wiring.
Examples
Uses a DatabaseConnection class with PostgreSQL settings, SQLAlchemy sessions, and an application entry point that selects a repository.
What you can do after
Operate/configure a shared SQLAlchemy database connection using environment variables and integrate it with a repository-based application.
How it connects
Connects database persistence with the Repository Pattern, SQLAlchemy, environment variables, and hexagonal architecture.

Also explained in

Compare how 6 books explain Singleton pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of AI-Powered Developer: Build software with ChatGPT and Copilot. The section links point to the parts of the book it draws on.