Skip to content

Latest commit

 

History

History
93 lines (61 loc) · 2.08 KB

File metadata and controls

93 lines (61 loc) · 2.08 KB

Singleton Pattern — Java & C++ Examples

This repository provides a minimal and easy-to-understand implementation of the Singleton design pattern in Java and C++. The goal is to help students learn how the pattern works, why it is used, and how to run simple example implementations on their own.


📌 What is the Singleton Pattern?

The Singleton pattern ensures that a class has only one instance during the program’s lifetime and provides a global point of access to it.

Typical use cases include:

  • Configuration managers
  • Logger classes
  • Database connection managers
  • Global state containers

Both examples in this repository demonstrate:

  • A private constructor
  • A static method that returns the single instance
  • Prevention of copying or instantiation from outside

✔ Java Example (Geeks.java)

This file shows a classical lazy-initialized Singleton in Java.

✔ C++ Example (main.cpp)

This file demonstrates a simple pointer-based Singleton implementation in C++ (and confirms that two calls return the same instance). The example corresponds to the uploaded code .


▶ How to Run the Examples

Run the Java Version

  1. Navigate to the folder:

    cd java
  2. Compile:

    javac Geeks.java
  3. Run:

    java Geeks

Run the C++ Version

  1. Navigate to the folder:

    cd cpp
  2. Compile:

    g++ main.cpp -o singleton
  3. Run:

    ./singleton

🧠 Learning Objectives

By experimenting with these files, you will learn:

  • How Singleton works in Java and C++
  • How constructors are hidden to prevent multiple instances
  • How static methods provide access to the single object
  • How memory allocation differs between languages (JVM vs manual C++)
  • Why Singleton must block copying (deleted copy constructor in C++)

🎓 License & Usage

This repository is created purely for educational purposes.

You are encouraged to modify the examples and experiment with alternative Singleton implementations.