Showing posts with label Design. Show all posts
Showing posts with label Design. Show all posts

Wednesday, August 26, 2026

Vector Database

 


What is a Vector Database?

Unstructured content (text, images, audio) is passed through an embedding model that converts the data into a list of numbers called a vector embedding. These vectors capture hidden patterns, intent, and semantic meaning.

A vector database stores and indexes these embeddings in high-dimensional space. Instead of matching literal text strings, it calculates mathematical proximity (using metrics like cosine similarity) to find the most conceptually similar results.

The 5-Step RAG Data Flow

Vector databases serve as the scalable memory layer for Retrieval-Augmented Generation (RAG) and LLM apps:

  1. Query Input: A user submits a prompt or document.

  2. Vector Conversion: An embedding model converts the input into a query vector.

  3. Storage & Search: The query vector is passed to the vector database.

  4. Similarity Retrieval: Fast nearest-neighbor search identifies the most contextually relevant documents.

  5. AI Generation: The AI application receives this retrieved context and generates an accurate, grounded response.

Key Takeaway

Traditional databases keep track of what your data is, while vector databases understand what your data means. Pairing them together forms the bedrock of fast, context-aware AI applications.

Friday, July 10, 2026

70 years of AI


If you think Artificial Intelligence is a brand-new invention born in the 2020s, you’re not alone—but you are about seven decades off.

While tools like ChatGPT and self-driving cars make it feel like we just crossed into the sci-fi future, the roots of AI stretch all the way back to the mid-20th century. Let’s take a look at how we got here, tracking the journey from academic theory to everyday reality.

1. The 1950s: The Birth of AI

The journey began with the founding fathers of computer science asking a fundamental question: Can machines think?

  • The Turing Test: In 1950, Alan Turing proposed a test to determine if a machine could exhibit intelligent behavior indistinguishable from a human.

  • Coining the Term: In 1956, John McCarthy officially coined the phrase "Artificial Intelligence" at the Dartmouth Conference, cementing it as a formal field of study.

2. The 1970s: The Era of "Expert Systems"

Instead of trying to teach a machine to learn everything, scientists shifted to coding strict, rule-based logic to solve highly specific problems.

  • MYCIN: A famous early AI rule-based system designed to detect blood infections and bacteria, helping doctors identify treatments based on a massive "if-then" logic web.

3. The 1990s: Machine Learning and Data Mining

The shift from hard-coded rules to statistical models allowed systems to actually "learn" patterns from data.

  • Data Clustering: Algorithms started grouping large datasets together without human intervention.

  • The 1997 Milestone: IBM's Deep Blue made global headlines by defeating world chess champion Garry Kasparov, proving that machines could outperform humans in deep, strategic calculations.

4. The 2010s: The Deep Learning Revolution

As computers grew exponentially more powerful and internet data exploded, AI underwent a massive renaissance.

  • Neural Networks Take Off: Artificial neural networks (mimicking human brain structures) began to excel at vision and language tasks.

  • AlphaGo (2016): Google DeepMind’s AlphaGo defeated Go world champion Lee Sedol. This was a massive leap forward because Go is a game of intuition and infinite possibilities, far more complex than chess.

5. The 2020s: AI in Everyday Life

Today, AI has stepped out of research labs and into our pockets.

  • Seamless Integration: It powers virtual assistants, autonomous vehicles, and highly precise healthcare diagnostics.

  • The New Era: The conversation has shifted from "Is AI possible?" to "How do we govern it safely?" with heavy focus on ethics, copyright, and global regulations.

 

Take Away

The "AI Boom" we are experiencing today didn't happen overnight. It is the result of 70+ years of steady evolution, academic persistence, and technological breakthroughs. We aren't watching the beginning of AI—we are watching its maturity.

Sunday, June 7, 2026

Network terms

 


1. Latency (The "Delay")

  • What it is: The time it takes for a single piece of data (a packet) to travel from the sender to the receiver.

  • The Analogy: This is the speed limit or the time it takes for a single car to drive from City A to City B.

  • From the image: the end-to-end delay is shown as 40 ms. It measures the time for one single packet to reach its destination.

2. Throughput (The "Actual Data Delivered")

  • What it is: The actual amount of data that successfully reaches the destination per second.

  • The Analogy: This is the actual number of cars passing a specific point on the highway every minute. Traffic, accidents, or construction can slow this down.

  • From the image: Even if the road is wide, the delivered rate here is 62 Mbps of actual data moving through.

3. Bandwidth (The "Link Capacity")

  • What it is: The maximum potential rate that the network link can possibly carry. It’s the upper limit of your connection.

  • The Analogy: This is the number of lanes on the highway. A 6-lane highway can hold more cars at once than a 2-lane highway, but it doesn't guarantee the cars will move faster if there's traffic.

  • From the image: The total link capacity is 100 Mbps.

In simple context, Bandwidth as the size of the pipe, Throughput as how much water is actually flowing through it right now, and Latency as how fast the first drop of water hits your glass.

Sunday, November 23, 2025

AI Tools 2025 Pyramid

 


Level 1: Foundational Services

At the very base of the pyramid are the foundational AI services, which often work behind the scenes or provide core functionalities for more complex tasks.

  • RecCloud (Video Translation Service): In an increasingly globalized world, video content is king. RecCloud helps break down language barriers by providing video translation services, making your content accessible to a wider international audience.

  • Tidio (Customer Service): Excellent customer service is paramount for any business. Tidio leverages AI to power chatbots and streamline customer interactions, providing instant support and freeing up human agents for more complex issues.

  • Zapier (Multi-platform Integration): While not strictly an "AI tool" in itself, Zapier is crucial for integrating various AI tools and automating workflows across different platforms. It acts as the connective tissue, allowing your AI applications to communicate seamlessly.

  • Calendly (Schedule Management): AI-powered scheduling tools like Calendly take the hassle out of booking appointments. They can intelligently find the best times, send reminders, and manage your calendar, optimizing your time.

  • PicWish (Image Generation): As we move towards more visual content, AI image generation tools like PicWish are becoming indispensable. They allow users to create stunning visuals from text prompts, saving time and resources on graphic design.

Level 2: Design Tools

The next level up focuses on AI tools that assist in design and creative endeavors, empowering both professionals and casual users to produce high-quality visuals and experiences.

  • Midjourney (Image Generation): A powerful generative AI tool, Midjourney allows users to create incredibly detailed and artistic images from simple text descriptions, pushing the boundaries of visual creativity.

  • Recraft (Image Generation): Similar to Midjourney, Recraft also specializes in AI-powered image generation, providing another avenue for creating unique visual content for various applications.

  • Figma (Design Collaboration): While Figma is primarily a UI/UX design tool, its collaborative features can be enhanced with AI plugins, streamlining design processes and team communication.

  • Canva (Design Tool): Canva has democratized design, and with its increasing integration of AI features, it makes graphic design accessible to everyone, offering smart recommendations and automated design elements.

Level 3: Writing Assistants

AI writing assistants are revolutionizing content creation, helping with everything from drafting emails to generating long-form articles.

  • ChatGPT (Writing Assistant): A household name, ChatGPT is a versatile AI language model capable of generating human-like text, answering questions, summarizing information, and assisting with various writing tasks.

  • Claude (Writing Assistant): Another advanced AI assistant, Claude excels at complex reasoning and generating coherent, thoughtful responses, making it ideal for in-depth content creation and analysis.

  • Grok (Writing Assistant): Grok, with its real-time knowledge access, offers unique capabilities for generating timely and relevant content, especially useful for news and current affairs.

Level 4: Market Research

At this level, AI tools become more strategic, assisting with data analysis and market insights to inform business decisions.

  • Perplexity (Market Research): Perplexity combines powerful search capabilities with AI summarization, making it an excellent tool for quickly gathering and understanding information for market research.

  • Gemini (Market Research): Google's Gemini is a multimodal AI that can process and understand various types of information, making it a robust tool for comprehensive market analysis and trend identification.

Level 5: Code Editor

At the pinnacle of the pyramid lies the most specialized and advanced AI application for developers.

  • Cursor (Code Editor): Cursor is an AI-powered code editor that assists developers by suggesting code, identifying errors, and even generating entire functions, significantly accelerating the coding process and improving code quality.

Thursday, October 16, 2025

API Migration Journey


On working recent api migration, it triggered me to write comprehensive and suitable journey of API design growth for a technical audience. 

SOAP

  • Illustration:

    • SOAP Sender: Represents a client application initiating a request.

    • Protocol (HTTP/SMTP): The transport layer over which SOAP messages are sent. Messages are typically XML-based.

    • SOAP Message (Envelope): A structured XML document containing the message body, header, and fault information.

    • SOAP Receiver: A server-side application parsing the SOAP message, processing the request, and sending a SOAP response.

    • Key Characteristics:

      • Strictly Typed: Uses XML Schema Definition (XSD) for message structure.

      • WSDL: Web Services Description Language describes the operations a web service offers.

      • Stateless: Each request is independent.

      • Synchronous/Asynchronous: Can support both.

      • Security: Built-in WS-Security standards.

      • Reliability: WS-ReliableMessaging for guaranteed delivery.

  • Use Case: Enterprise-level financial transactions, legacy system integration, highly distributed environments requiring ACID transactions and formal contracts.

  • Pros: High reliability, security, ACID compliance, language independence, extensive tooling.

  • Cons: Complex, verbose XML, higher overhead, steeper learning curve.

REST

  • Illustration:

    • Sender (Client): Sends HTTP requests (GET, POST, PUT, DELETE) to a server.

    • HTTP Request: Contains method, URL, headers, and optional body.

    • REST Web Server: Processes requests, accesses resources, and sends back HTTP responses.

    • HTTP Response: Contains status code, headers, and resource representation (e.g., JSON, XML).

    • Key Characteristics:

      • Stateless: Server doesn't store client context between requests.

      • Cacheable: Responses can be cached to improve performance.

      • Client-Server: Clear separation of concerns.

      • Layered System: Intermediaries (proxies, load balancers) can be introduced.

      • Uniform Interface: Resources identified by URIs, standard HTTP methods.

      • Self-Descriptive Messages: Messages contain enough info to be processed.

      • HATEOAS (Hypermedia As The Engine Of Application State): Optional, but a core principle for discoverability.

  • Use Case: Mobile application backend for a social networking platform, public APIs, web services requiring scalability and simplicity.

  • Pros: Simple, flexible, widely adopted, efficient (JSON is light), scalable, cacheable.

  • Cons: No strict contract (can lead to integration issues), lack of type safety, under/over-fetching data for complex queries.

GraphQL

  • Illustration:

    • Sender (Client): Sends a single HTTP POST request to a GraphQL server.

    • GraphQL Query/Mutation: A flexible query string defining exactly what data the client needs.

    • GraphQL Server: Parses the query, resolves fields by interacting with various data sources (databases, other APIs), and constructs a single JSON response.

    • Database/Other APIs: Data sources from which the GraphQL server fetches information.

    • Key Characteristics:

      • Single Endpoint: All queries go to one URL.

      • Declarative Data Fetching: Clients specify data requirements.

      • Schema Definition Language (SDL): Defines types, fields, and relationships.

      • Resolvers: Functions that fetch data for specific fields.

      • Strongly Typed: Prevents many runtime errors.

      • No Over/Under-fetching: Clients get exactly what they ask for.

  • Use Case: Real-time collaborative document editing, complex UIs needing data from multiple sources, microservices aggregation layer, mobile applications to reduce network requests.

  • Pros: Efficient data fetching, strong typing, better developer experience (IDE support), versionless APIs.

  • Cons: Caching complexity (due to POST requests), steeper learning curve than REST for basic use, file upload can be tricky.

gRPC

  • Illustration:

    • Client (abc): Makes a remote procedure call to a server.

    • Protocol Buffers (010010): A language-neutral, platform-neutral, extensible mechanism for serializing structured data. Used for defining service interfaces and message structures.

    • gRPC Server (Database Icon): Receives the call, executes the procedure, and returns a response.

    • HTTP/2: The underlying transport layer for multiplexing, streaming, and efficient connections.

    • Key Characteristics:

      • Contract-First: Uses Protocol Buffers (or other IDLs) to define service methods and message types.

      • High Performance: Binary serialization (Protobufs) and HTTP/2 for efficient data transfer.

      • Streaming: Supports unary, server-side, client-side, and bi-directional streaming.

      • Polyglot: Code generation for many languages.

      • Strongly Typed: Ensured by Protobuf definitions.

  • Use Case: Microservices communication in a distributed system, inter-service communication, high-performance computing, real-time data streaming.

  • Pros: High performance, low latency, efficient serialization, strong contracts, multi-language support, built-in streaming.

  • Cons: Browser support requires a proxy, not human-readable payload, steeper learning curve, limited tooling compared to REST.

Websocket

  • Illustration:

    • Sender (Client): Initiates an HTTP Upgrade request to establish a WebSocket connection.

    • HTTP Upgrade: Handshake process to upgrade from HTTP to WebSocket protocol.

    • Web Server (Building): Accepts the upgrade, establishing a persistent, full-duplex connection.

    • Full Duplex: Both client and server can send and receive messages simultaneously over the same open connection.

    • Key Characteristics:

      • Persistent Connection: A single, long-lived connection.

      • Full-Duplex: Bi-directional communication.

      • Low Overhead: After the initial handshake, minimal frame overhead.

      • Real-time: Ideal for immediate data exchange.

      • Event-Driven: Messages pushed from server to client.

  • Use Case: Live sports score updates, chat applications, real-time dashboards, online gaming, stock tickers.

  • Pros: Real-time communication, low latency, efficient for frequent small messages, reduced server load compared to polling.

  • Cons: More complex to implement than HTTP requests, requires server infrastructure to manage persistent connections, no built-in error handling/retries like HTTP.

Webhook

  • Illustration:

    • Source Application (Server with Gears): An event occurs (e.g., order fulfillment).

    • Async (Red Dotted Line): The source application asynchronously sends an HTTP POST request.

    • Payload (Gear Icon in Box): The POST request contains data about the event, typically JSON.

    • Webhook Listener/Receiver (Server Stack): A designated URL (endpoint) on a different server that is configured to receive these notifications.

    • Automated Order Fulfillment: The receiving system processes the event data.

    • Key Characteristics:

      • Event-Driven: Triggered by specific events.

      • HTTP POST: Typically uses POST requests to deliver data.

      • Asynchronous: The source doesn't wait for a response from the receiver.

      • Subscription Model: The receiver "subscribes" to events from the source by providing a callback URL.

      • Payloads: Data included in the POST request.

      • Retries/Error Handling: Often implemented by the source application for reliability.

  • Use Case: Automated order fulfillment notifications in e-commerce, GitHub commit notifications, payment gateway callbacks, CRM updates, CI/CD pipeline triggers.

  • Pros: Real-time updates, reduced polling overhead, efficient for event propagation, simple to implement for basic use cases.

  • Cons: Requires the receiver to have a publicly accessible URL, security concerns (verifying source), managing retries and failures, potential for "noisy" notifications if not filtered.

Wednesday, October 15, 2025

Browser workflow


Rocky wrote a simple and powerful workflow of web browser.  Here it is

When you type a URL into your browser:

  • The browser breaks the URL into components like scheme (e.g., "https"), domain (e.g., "example.com"), and path (e.g., "/page").
  • If the IP address isn’t cached, it queries a DNS server to resolve it.
  • A connection is established with the web server using the IP and port (80 for HTTP, 443 for HTTPS).
  • The browser sends an HTTP request to fetch the resource.
  • The server responds with the requested data (HTML, CSS, JS) and a status code.
  • The browser renders the page by processing the HTML, applying CSS, and executing JavaScript.
  • Secure sites establish an SSL/TLS connection for encryption.
  • Resources are cached to speed up future visits.
  • Fast, secure, and seamless—all thanks to modern browsers!

Friday, July 11, 2025

AI Journey VBlog

 

 

Blog content is created by AI from my first V(ideo)Blog at https://www.youtube.com/playlist?list=PLClRWhkU0HEcZo2jDgscHa0UGcld6v7ZP.

  • Evolution of AI in Industry Ganesan Senthilvel outlined the four phases of AI's industrial evolution, beginning in 1943 with neuron research and progressing to machine learning and deep learning. They explained that the rise of social media around 2010 shifted data from structured to unstructured formats, necessitating high-powered GPU computing and neural algorithms to process large volumes of unstructured data.
  • AI Concepts and Models Ganesan Senthilvel detailed key AI concepts such as training data, model building, and automatic inference, noting that ML data mining identifies patterns for prediction. They explained regression models are foundational for big data predictions and that recurrent neural networks process sequences of words by feeding results back into the processing layer.
  • Generative AI and Recent Innovations Ganesan Senthilvel discussed the recent explosion in AI's popularity, attributing it to generative AI, particularly ChatGPT, which reached one million users in just five days. They highlighted the difference between traditional AI, which analyzes existing information, and generative AI, which produces entirely new content like text, images, or code. They also introduced Retrieval-Augmented Generation (RAG) for trusted information retrieval and Agentic AI for building complex business workflows, in addition to the Model Context Protocol (MCP) framework for universal AI model communication.
  • AI System Layers and Learning Approach Ganesan Senthilvel described the five distinct layers of an AI system, starting with the interaction layer as the foundation and moving up through intelligent, engineering, observability, and agent layers, where human and AI interact. They emphasized that hands-on coding and consistent daily learning are crucial for staying current in computer engineering and becoming an engineering leader.

Friday, January 3, 2025

git merge vs rebase


What are the differences to use git merge and git rebase commands and their execution model? 

Git Merge 

This creates a new commit 'G' in the main branch. G ties the histories of both main and feature branches. 

Git merge is nondestructive in nature i.e. neither the main nor the feature branch is changed. 

Git Rebase 

It moves the feature branch histories to the head of the main branch. It creates new commits E, F and G for each commit in the feature branch. 

The benefit of rebase is that it has linear commit history.  Rebase can be dangerous if the golden rule of git rebase is not followed. 

ByteByteGo clearly describes the details in the given diagram

Wednesday, October 2, 2024

Adapter Pattern

What

Adapter structural design pattern is a bridge between two incompatible interfaces by converting the interface of a class into another interface that a client expects. It is useful when integrating legacy components with new systems or when creating a reusable library.

Who

It has four key actors (1) Target Interface (2) Adapter (3) Adaptee (4) Client.

1. Target interface is the common interface that the client code interacts with.

2. Adapter is a bridge to adapt the interface of the adaptee to match the target interface.

3. Adaptee is existing system with an incompatible interface to be integrated into new system

4. Client is unaware of the specific implementation of the adaptee and the adapter.

How

Adapter implements the ITarget interface and translates request method to the SpecificRequest method of the Adaptee. The client code interacts with the adapter.

<pre><code>

// Target Interface

public interface ITarget

{

    string Request();

}


// Adaptee

public class Adaptee

{

    public string SpecificRequest()

    {

        return "Adaptee's specific request";

    }

}


// Adapter

public class Adapter : ITarget

{

    private readonly Adaptee _adaptee;


    public Adapter(Adaptee adaptee)

    {

        _adaptee = adaptee;

    }


    public string Request()

    {

        return _adaptee.SpecificRequest();

    }

}


// Client

public class Client

{

    public void Execute(ITarget target)

    {

        Console.WriteLine(target.Request());

    }

}


// Usage

class Program

{

    static void Main()

    {

        Adaptee adaptee = new Adaptee();

        ITarget adapter = new Adapter(adaptee);


        Client client = new Client();

        client.Execute(adapter);

    }

}

</code></pre>

Why

  • Reusability: Allows the reuse of existing client code with new systems.
  • Decoupling: Decouples the client from the specific implementation of the payment gateways.
  • Flexibility: Makes it easy to switch between different implementations without modifying the client code.

When

  • When you need to use an existing class but its interface is not compatible with the rest of your code.
  • When you want to create a reusable class that can work with unrelated or unforeseen classes.

Reference

Code repository: https://github.com/gsenthilvel/DesignStructural


Thursday, September 12, 2024

Builder Pattern

What

Builder pattern allows the product construction in a step-by-step fashion. Though construction process can vary based on product type, it separates the construction of a complex object from its representation

Who

It has four key actors (1) Product (2) Builder (3) Concrete Builder (4) Director.

1. Product is the complex object that the Builder pattern is responsible for constructing.

2. Builder is an interface or an abstract class that declares the construction steps for building a complex object.

3. ConcreteBuilder implements the interface to provide specific implementations for building each part of the product.

4. Director is responsible for managing the construction process of the complex object.

How

(1) Construction steps are defined in the Builder interface. 

(2) Concrete Builder implements the interface to provide specific implementations for building each part of the product. 

(3) Director is responsible for managing the construction

(4) Client class creates the Director object and passes the ConcreteBuilder object to the Director object.

<pre><code>

public void Construct()

        {

            _builder.SetCPU();

            _builder.SetRAM();

            _builder.SetStorage();

            _builder.SetGPU();

            _builder.SetDisplay();

            _builder.SetOS();

            _builder.GetLaptop().ShowInfo();

        }

</code></pre>

When

Builder design pattern is best suitable for any job execution framework, where the job execution steps are common, but the job execution order can vary like Quartz job scheduler in system programming.

In the given example, the builder pattern is used to create a laptop with different configurations.

Reference

Code repository: https://github.com/gsenthilvel/DesignCreational/tree/main/prototype


Saturday, September 7, 2024

Prototype Pattern


What

Prototype design pattern is a creational pattern to create new objects by copying an existing object, known as a prototype. This pattern is particularly useful when the cost of creating a new object is high or complex.

Who

It has three key actors (1) Prototype Interface (2) Concrete Prototype (3) Client.

  1. Prototype Interface provides a blueprint for creating new objects by specifying the cloning contract.
  2. Concrete Prototype is a class that implements the clone method with cloning logic specific to the class
  3. Abstract Product is a class to initiate the cloning process without being aware of the concrete classes involved.

Where

Though prototype is similar to base/derived classes, it is more focused on object creation by cloning

  1. Design: Prototype pattern focuses on object creation by cloning, whereas a base class focuses on defining a common interface and shared behavior for derived classes.
  2. Flexibility: Prototype is more flexible when it comes to creating objects dynamically at runtime, while base classes are more static and defined at compile-time.

As a side effect, it is not advisable to use prototype pattern when objects are immutable (unchangeable) and do not need variations,

How

End user promotes a clear separation between the creation of product families with cars and their specifications. It has the following key steps:

  1. Create Prototype interface for concrete class with clone operation.
  2. Create concrete prototype class with member wise cloning from the above interface.
  3. Client class to create new objects by cloning the prototype object.

<pre><code>

public interface IObjectPrototype

{

IObjectPrototype Clone();

}

</code></pre>

When

Prototype is best fit when object creation is complex and resource-intensive- classic example is Microsoft Word.  When users create a new document, they often start from a template in Microsoft Word. 

Prototype pattern helps to clone a template document instead of creating a new document from scratch.

Reference

Code repository: https://github.com/gsenthilvel/DesignCreational/tree/main/prototype

Tuesday, September 3, 2024

Abstract Factory Pattern


What

Abstract Factory Pattern is another layer of abstraction over Factory pattern. It is used to create families of related objects without specifying their concrete classes. 

It provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.

Who

It has four key actors as below

  1. Abstract Factory is an interface for creating a family of related objects, but it does not specify the concrete classes of the objects to be created.
  2. Concrete Factory is a class that implements the Abstract Factory interface to create a family of related objects.
  3. Abstract Product is an interface for a type of product. 
  4. Concrete Product is a class that implements the Abstract Product interface to create a specific type of product.

How

End user promotes a clear separation between the creation of product families with cars and their specifications. It has the following key steps:

  • Create an interface for the Abstract Factory with a method to create a family of related objects.
  • Create an interface for the Abstract Product with a method to describe the product.
  • Create a Concrete Factory class that implements the Abstract Factory interface to create a family of related objects.
  • Create a Concrete Product class that implements the Abstract Product interface to describe the product.
  • Create a client class that uses the Abstract Factory and Abstract Product interfaces to create and describe a family of related objects.

When

Classic real-life example of Abstract Factory pattern is GUI toolkit like button, checkbox, menu across different operating systems like Windows, Linux Mac.

Where

Though Factory and Abstract Factory look similar, it has significant differences

Factory pattern has three key elements 

  1. create objects without mentioning exact class 
  2. single product type focus with less complexity
  3. lower-level abstraction

Abstract factory pattern has the following key elements

  1. create family of related objects without specification 
  2. multiple product type focus with more complexity
  3. higher level abstraction

Reference

Code repository https://github.com/gsenthilvel/DesignCreational/tree/main/abstractfactory

Sunday, September 1, 2024

Factory Pattern



Factory pattern is one of the most used creational design pattern in real world applications, like DB, Logging frameworks. It is used to create objects based on a common interface.

Without Factory

End user is responsible for creating the object by directly instantiating the class based on the input type during its construction.  It has limitation of tightly coupling, limited scalability and single responsibility violation.

<pre><code>

if (carModel == 1)

{

_evCar = new Tesla();

}

</code></pre>

With Factory

Two key actors in Factory design (1) underlying product (2) creator factory. Both actors are driven by interface with multiple derived classes.

It is a design pattern that provides an interface for creating objects in a superclass,  but allows subclasses to alter the type of objects that will be created.

<pre><code>

ICarFactory carFactory = new CarFactory();

_evCar = carFactory.GetCar(carModel);

</code></pre>

Benefits

The Factory pattern is useful when you need to create an object based on a specific input or condition. It has few design advantages like: decoupling of creation logic with client usage, code reusability, scalability with extensibility and single responsibility principle.

Reference

Code repository: https://github.com/gsenthilvel/DesignCreational/tree/main/factory 


Saturday, August 24, 2024

Singleton Pattern


One of the easiest models, used in Creational design pattern

What?

It is a design pattern that restricts the instantiation of a class to one object. 

This is useful when exactly one object is needed to coordinate actions across the system.

Why?

I can think of a few scenarios where the Singleton pattern is useful.

On usage of a shared resource, like a database connection, or a logger, Singleton pattern makes sure that it has one instance of that resource.

When?

When you need to have a single instance of a class, and you want to provide a global point of access to the object.

It can be instantiated in two ways, either lazy or eager.

1. Eager instantiation is when the object is created when the class is loaded.

2. Lazy instantiation is when the object is created only when it is needed.

<pre><code>

private static readonly Lazy<Singleton> _instance = 

            new Lazy<Singleton>(() => new Singleton());

</code></pre>

How?

Key components of Singleton pattern are:

1. Static member: 

Static member ensures that memory is allocated only once, preserving the single instance of the Singleton class.

<pre><code>

private static Singleton instance;

</code></pre>

2. Private constructor:

Private constructor ensures that the class cannot be instantiated from outside the class.

<pre><code>

private Singleton() {}

</code></pre>

3. Public static method:

Public static method provides a global point of access to the Singleton object.

<pre><code>

public static Singleton Instance

{

get

{

return _instance.Value;

}

}

</code></pre>

Where?

Code repository: DesignCreational/singleton at main · gsenthilvel/DesignCreational (github.com)