DesignPatterns.Creational.Net 26.2.12.1

dotnet add package DesignPatterns.Creational.Net --version 26.2.12.1
                    
NuGet\Install-Package DesignPatterns.Creational.Net -Version 26.2.12.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DesignPatterns.Creational.Net" Version="26.2.12.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DesignPatterns.Creational.Net" Version="26.2.12.1" />
                    
Directory.Packages.props
<PackageReference Include="DesignPatterns.Creational.Net" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DesignPatterns.Creational.Net --version 26.2.12.1
                    
#r "nuget: DesignPatterns.Creational.Net, 26.2.12.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DesignPatterns.Creational.Net@26.2.12.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DesignPatterns.Creational.Net&version=26.2.12.1
                    
Install as a Cake Addin
#tool nuget:?package=DesignPatterns.Creational.Net&version=26.2.12.1
                    
Install as a Cake Tool

DesignPatterns.Creational.Net

NuGet Build Status License .NET

A production-ready .NET library implementing the Gang of Four (GoF) Creational Design Patterns. This library provides well-tested, documented interfaces, base classes, and example implementations using modern C# features.

Table of Contents

Features

  • Factory Pattern - Create objects without specifying their exact classes
  • Abstract Factory Pattern - Create families of related objects
  • Builder Pattern - Construct complex objects step by step
  • Prototype Pattern - Clone objects efficiently
  • Singleton Pattern - Ensure a class has only one instance

Multi-Target Framework Support

Supports .NET 6.0, 7.0, 8.0, 9.0, and 10.0:

  • net6.0
  • net7.0
  • net8.0
  • net9.0
  • net10.0

Installation

dotnet add package DesignPatterns.Creational.Net

Or via Package Manager Console:

Install-Package DesignPatterns.Creational.Net

Quick Start

using DesignPatterns.Creational.Net.Factory;
using DesignPatterns.Creational.Net.Builder.Examples;
using DesignPatterns.Creational.Net.Singleton.Examples;

// Factory: Create objects without specifying their exact classes
var factory = new DocumentFactory("MyDoc", "Content");
var document = factory.Create();

// Builder: Construct complex objects with a fluent API
var request = new HttpRequestBuilder()
    .WithMethod("GET")
    .WithUrl("https://api.example.com")
    .Build();

// Singleton: Access a single shared instance
var config = ConfigurationManager.Instance;
config.SetSetting("Environment", "Production");

Usage Examples

Factory Pattern

using DesignPatterns.Creational.Net.Factory.Examples;

// Create a document factory
var factory = new DocumentFactory("MyDoc", "Initial content");
var document = factory.Create();
document.Execute();

Abstract Factory Pattern

using DesignPatterns.Creational.Net.AbstractFactory;
using DesignPatterns.Creational.Net.AbstractFactory.Examples;

// Create a modern UI factory
IAbstractFactory<IProductA, IProductB> factory = new ModernUIFactory();
var button = factory.CreateProductA();
var checkbox = factory.CreateProductB();

button.OperationA();
checkbox.OperationB();

Builder Pattern

using DesignPatterns.Creational.Net.Builder.Examples;

// Build an HTTP request fluently
var request = new HttpRequestBuilder()
    .WithMethod("POST")
    .WithUrl("https://api.example.com/data")
    .WithHeader("Content-Type", "application/json")
    .WithBody("{\"key\":\"value\"}")
    .Build();

// Build a computer using the traditional builder
var builder = new ComputerBuilder();
builder.SetCPU("Intel i9");
builder.SetRAM(32);
builder.SetStorage(1024);
builder.EnableWiFi();
var computer = builder.Build();

Prototype Pattern

using DesignPatterns.Creational.Net.Prototype.Examples;

// Clone a shape
var original = new Shape("Circle", "Red", 10, 20);
var clone = ((IPrototype<Shape>)original).Clone();

// Use the prototype registry
var registry = new PrototypeRegistry<string, Shape>();
registry.Register("circle", original);
var clonedShape = registry.Clone("circle");

Singleton Pattern

using DesignPatterns.Creational.Net.Singleton.Examples;

// Access singleton instance
var config = ConfigurationManager.Instance;
config.SetSetting("key", "value");

// Custom singleton with initialization
Singleton<Logger>.Initialize(() => new Logger("/tmp/app.log"));
var logger = Singleton<Logger>.Instance;
logger.Log("Application started");

Pattern Details

Factory Pattern

  • IFactory<TProduct> - Factory interface
  • IProduct - Product marker interface
  • ProductBase - Base product implementation
  • Examples: DocumentFactory, NotificationFactory

Abstract Factory Pattern

  • IAbstractFactory<TProductA, TProductB> - Abstract factory interface
  • IProductA, IProductB - Product family interfaces
  • Examples: ModernUIFactory, ClassicUIFactory

Builder Pattern

  • IBuilder<TProduct> - Traditional builder interface
  • IFluentBuilder<TBuilder, TProduct> - Fluent builder interface
  • Director<TProduct> - Director for orchestrating builds
  • Examples: HttpRequestBuilder, ComputerBuilder

Prototype Pattern

  • IPrototype<T> - Prototype interface with shallow and deep clone
  • PrototypeBase<T> - Base implementation
  • PrototypeRegistry<TKey, TPrototype> - Registry for managing prototypes
  • Examples: Shape (record), Document (class)

Singleton Pattern

  • SingletonBase<T> - Base singleton with lazy initialization
  • Singleton<T> - Singleton with custom initialization
  • ThreadSafeSingleton<T> - Double-check locking implementation
  • Examples: ConfigurationManager, DatabaseConnection, Logger

Modern C# Features

This library leverages modern C# features:

  • Records - Immutable data types with built-in cloning (Shape)
  • Init-only properties - Immutable object initialization
  • Nullable reference types - Compile-time null safety
  • Pattern matching - Expression-based control flow
  • LINQ - Functional data processing (PrototypeRegistry.GetRegisteredKeys())

When to Use Each Pattern

Pattern Use When Avoid When
Factory You need to create objects without specifying their exact classes<br>• Creating different types based on configuration<br>• Encapsulating object creation logic Object creation is simple and straightforward
Abstract Factory You need to create families of related objects<br>• Building cross-platform UI components<br>• Creating themed product sets You only have one type of product to create
Builder Objects have many optional parameters<br>• Construction is complex with multiple steps<br>• You want immutable objects with flexible initialization Object has few parameters and simple construction
Prototype Creating new objects is expensive<br>• You need to clone existing objects<br>• Objects have many similar instances Objects are simple to construct from scratch
Singleton Exactly one instance must exist<br>• Global access point is needed<br>• Lazy initialization is required You need multiple instances or testability is important

Performance Considerations

Singleton Pattern

  • Thread-Safe: All singleton implementations use thread-safe initialization
  • Lazy Loading: Instances are created only when first accessed
  • Memory: Single instance per type, minimal memory overhead

Prototype Pattern

  • Shallow Clone: Fast, copies references (use for immutable members)
  • Deep Clone: Slower, creates new instances (required for mutable nested objects)
  • Records: Leverage C# records for efficient immutable cloning

Builder Pattern

  • Fluent API: No performance overhead, returns same builder instance
  • Immutability: Creates final object only once in Build() method

Factory & Abstract Factory

  • Minimal Overhead: Simple object instantiation
  • Caching: Consider caching expensive-to-create products

Testing

The library includes comprehensive unit tests covering all patterns:

dotnet test

All 32+ tests validate the functionality and thread safety of each pattern.

Test Coverage

  • ✅ Factory pattern creation and polymorphism
  • ✅ Abstract factory product families
  • ✅ Builder fluent interface and immutability
  • ✅ Prototype shallow and deep cloning
  • ✅ Singleton thread safety and lazy initialization
  • ✅ Error handling and edge cases

Documentation

All public APIs include XML documentation with:

  • Summary descriptions
  • Parameter descriptions
  • Return value descriptions
  • Exception documentation
  • Usage examples

API Documentation

Generate API documentation using your favorite documentation generator:

# Using DocFX
dotnet tool install -g docfx
docfx init
docfx build

FAQ

Q: Can I use multiple patterns together?

A: Yes! Patterns are often combined. For example, use Abstract Factory with Builder, or Singleton with Factory.

Q: Is this library thread-safe?

A: Yes. All singleton implementations are thread-safe. Other patterns don't maintain shared state, so they're inherently thread-safe.

Q: Why use this library instead of implementing patterns myself?

A: This library provides:

  • Well-tested implementations
  • Comprehensive XML documentation
  • Modern C# features and best practices
  • Multiple framework support (.NET 6-10)
  • Production-ready code

Q: Can I extend the base classes?

A: Absolutely! All base classes (ProductBase, PrototypeBase, SingletonBase) are designed for inheritance.

Q: How do I choose between Factory and Abstract Factory?

A: Use Factory for single product types. Use Abstract Factory when you need to create families of related products that work together.

Q: Should I always use Singleton for global state?

A: Not necessarily. Consider dependency injection and testability. Singleton is best when you truly need exactly one instance and global access.

Roadmap

Planned Enhancements

  • Add async factory and builder support
  • Object pooling integration with Prototype pattern
  • Serialization support for all patterns
  • Performance benchmarks and optimization guide

Completed

  • All 5 GoF creational patterns
  • Multi-target framework support (.NET 6-10)
  • Comprehensive unit tests
  • XML documentation
  • Modern C# features (records, nullable reference types)

License

See LICENSE file for details.

Contributing

Contributions are welcome! This library follows standard .NET coding conventions and design pattern best practices.

How to Contribute

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Guidelines

  • Follow existing code style and conventions
  • Add unit tests for new features
  • Update documentation and XML comments
  • Ensure all tests pass
  • Keep patterns implementation faithful to GoF definitions
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
26.2.12.1 88 2/12/2026