{"id":23,"date":"2020-06-23T10:11:00","date_gmt":"2020-06-23T09:11:00","guid":{"rendered":"https:\/\/debuggersspace.com\/index.php\/2020\/06\/23\/design-patterns-in-net\/"},"modified":"2025-04-09T19:23:12","modified_gmt":"2025-04-09T18:23:12","slug":"design-patterns-in-net","status":"publish","type":"post","link":"https:\/\/debuggersspace.com\/index.php\/2020\/06\/23\/design-patterns-in-net\/","title":{"rendered":"Overview of some popular design patterns in each category, along with their use cases in .NET Core"},"content":{"rendered":"<div class='booster-block booster-read-block'>\n                <div class=\"twp-read-time\">\n                \t<i class=\"booster-icon twp-clock\"><\/i> <span>Read Time:<\/span>4 Minute, 0 Second                <\/div>\n\n            <\/div><p>&nbsp;<\/p>\n<style>\n        body {<br \/>\n            font-family: Arial, sans-serif;<br \/>\n            line-height: 1.6;<br \/>\n            margin: 0;<br \/>\n            padding: 0px;<br \/>\n            background-color: #f4f4f9;<br \/>\n        }<br \/>\n        h2 {<br \/>\n            color: #333;<br \/>\n        }<br \/>\n        pre {<br \/>\n            background-color: #000;<br \/>\n            color: #fff;<br \/>\n            padding: 10px;<br \/>\n            border-radius: 4px;<br \/>\n            overflow-x: auto;<br \/>\n        }<br \/>\n        code {<br \/>\n            color: #ff7f50;<br \/>\n        }<br \/>\n        .tricky-question {<br \/>\n            background-color: #eee;<br \/>\n            padding: 10px;<br \/>\n            margin: 15px 0;<br \/>\n            border-left: 5px solid #ff7f50;<br \/>\n        }<br \/>\n    <\/style>\n<p>&nbsp;<\/p>\n<h2>Design Patterns in .NET Core<\/h2>\n<p>Design patterns are critical for writing scalable and maintainable applications in <strong>.NET Core<\/strong>. They allow developers to address common software design challenges and improve code reuse, flexibility, and readability. Below is a breakdown of key patterns used in .NET Core along with tricky interview questions.<\/p>\n<h3>Creational Design Patterns<\/h3>\n<h4>1. Singleton Pattern<\/h4>\n<p><strong>Definition:<\/strong> The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is commonly used for scenarios like logging or configuration management in .NET Core.<\/p>\n<pre><code>public sealed class Logger {\r\n    private static Logger _instance;\r\n    private static readonly object _lock = new object();\r\n\r\n    private Logger() { }\r\n\r\n    public static Logger Instance {\r\n        get {\r\n            lock (_lock) {\r\n                if (_instance == null) {\r\n                    _instance = new Logger();\r\n                }\r\n                return _instance;\r\n            }\r\n        }\r\n    }\r\n}<\/code><\/pre>\n<div class=\"tricky-question\"><strong>Tricky Question:<\/strong> Can a Singleton class be inherited?<br \/>\n<strong>Answer:<\/strong> No, a Singleton class should not be inherited to ensure only one instance is created. Mark the class <code>sealed<\/code> to prevent inheritance.<\/div>\n<h4>2. Factory Method Pattern<\/h4>\n<p><strong>Definition:<\/strong> The Factory Method pattern provides an interface for creating objects but allows subclasses to alter the type of objects that will be created. It is ideal for situations where the exact class of objects is unknown until runtime.<\/p>\n<pre><code>public abstract class PaymentFactory {\r\n    public abstract IPayment CreatePayment();\r\n}\r\n\r\npublic class CreditCardFactory : PaymentFactory {\r\n    public override IPayment CreatePayment() {\r\n        return new CreditCardPayment();\r\n    }\r\n}\r\n\r\npublic class PayPalFactory : PaymentFactory {\r\n    public override IPayment CreatePayment() {\r\n        return new PayPalPayment();\r\n    }\r\n}<\/code><\/pre>\n<div class=\"tricky-question\"><strong>Tricky Question:<\/strong> How does the Factory Method promote loose coupling?<br \/>\n<strong>Answer:<\/strong> It decouples object creation from the implementation by abstracting the instantiation process, allowing flexibility in creating objects.<\/div>\n<h4>3. Dependency Injection (DI)<\/h4>\n<p><strong>Definition:<\/strong> DI is a technique where the dependencies of a class are injected by an external entity. .NET Core has built-in support for DI, making it easy to manage service lifetimes.<\/p>\n<p><code>public class MyService {<br \/>\n    private readonly IMyDependency _dependency;<\/p>\n<p>    public MyService(IMyDependency dependency) {<br \/>\n        _dependency = dependency;<br \/>\n    }<br \/>\n}<\/p>\n<p><a href=\"https:\/\/debuggersspace.com\/index.php\/2025\/04\/09\/understanding-dependency-injection-and-ioc-in-net-core-a-beginner-friendly-guide-with-real-world-examples\/\" target=\"_blank\" rel=\"noopener\">Click here -<\/a><\/code>Understanding Dependency Injection and IoC in .NET Core \u2013 A Beginner-Friendly Guide with Real-World Examples<\/p>\n<div class=\"entry-meta entry-meta-category\"><code><\/code><\/div>\n<div class=\"tricky-question\"><strong>Tricky Question:<\/strong> Why is Dependency Injection important for unit testing?<br \/>\n<strong>Answer:<\/strong> DI allows mocking dependencies during testing, which makes it easier to isolate and test individual components.<\/div>\n<h3>Structural Design Patterns<\/h3>\n<h4>1. Adapter Pattern<\/h4>\n<p><strong>Definition:<\/strong> The Adapter pattern allows incompatible interfaces to work together by converting the interface of a class into another interface that clients expect.<\/p>\n<pre><code>public interface ILogger {\r\n    void Log(string message);\r\n}\r\n\r\npublic class ThirdPartyLogger {\r\n    public void WriteLog(string log) {\r\n        Console.WriteLine(log);\r\n    }\r\n}\r\n\r\npublic class LoggerAdapter : ILogger {\r\n    private readonly ThirdPartyLogger _thirdPartyLogger;\r\n\r\n    public LoggerAdapter(ThirdPartyLogger thirdPartyLogger) {\r\n        _thirdPartyLogger = thirdPartyLogger;\r\n    }\r\n\r\n    public void Log(string message) {\r\n        _thirdPartyLogger.WriteLog(message);\r\n    }\r\n}<\/code><\/pre>\n<div class=\"tricky-question\"><strong>Tricky Question:<\/strong> How does the Adapter pattern promote reusability?<br \/>\n<strong>Answer:<\/strong> By allowing existing classes to work with new clients without modifying the original code, promoting code reuse.<\/div>\n<h4>2. Decorator Pattern<\/h4>\n<p><strong>Definition:<\/strong> The Decorator pattern allows behavior to be added to an object dynamically without modifying its structure. This is useful when behavior needs to change based on the context.<\/p>\n<pre><code>public interface INotifier {\r\n    void Send(string message);\r\n}\r\n\r\npublic class EmailNotifier : INotifier {\r\n    public void Send(string message) {\r\n        Console.WriteLine($\"Email sent: {message}\");\r\n    }\r\n}\r\n\r\npublic class SMSDecorator : INotifier {\r\n    private readonly INotifier _notifier;\r\n\r\n    public SMSDecorator(INotifier notifier) {\r\n        _notifier = notifier;\r\n    }\r\n\r\n    public void Send(string message) {\r\n        _notifier.Send(message);\r\n        Console.WriteLine($\"SMS sent: {message}\");\r\n    }\r\n}<\/code><\/pre>\n<div class=\"tricky-question\"><strong>Tricky Question:<\/strong> When would you prefer the Decorator pattern over inheritance?<br \/>\n<strong>Answer:<\/strong> The Decorator pattern is preferable when you need to add behavior dynamically, while inheritance is more static and rigid.<\/div>\n<h3>Behavioral Design Patterns<\/h3>\n<h4>1. Observer Pattern<\/h4>\n<p><strong>Definition:<\/strong> The Observer pattern defines a one-to-many relationship where multiple objects (observers) are notified whenever the state of another object (subject) changes.<\/p>\n<pre><code>public class Subject {\r\n    public event Action Notify;\r\n\r\n    public void ChangeState() {\r\n        Notify?.Invoke();\r\n    }\r\n}\r\n\r\npublic class Observer {\r\n    public void Update() {\r\n        Console.WriteLine(\"Observer has been notified.\");\r\n    }\r\n}<\/code><\/pre>\n<div class=\"tricky-question\"><strong>Tricky Question:<\/strong> What is the difference between the Observer pattern and Pub\/Sub?<br \/>\n<strong>Answer:<\/strong> The Observer pattern has direct relationships between subjects and observers, while Pub\/Sub uses a message broker to decouple these relationships.<\/div>\n<h4>2. Command Pattern<\/h4>\n<p><strong>Definition:<\/strong> The Command pattern encapsulates a request as an object, allowing parameterization of clients, request queueing, and undo operations.<\/p>\n<pre><code>public interface ICommand {\r\n    void Execute();\r\n}\r\n\r\npublic class Light {\r\n    public void TurnOn() { Console.WriteLine(\"Light is On\"); }\r\n    public void TurnOff() { Console.WriteLine(\"Light is Off\"); }\r\n}\r\n\r\npublic class TurnOnCommand : ICommand {\r\n    private readonly Light _light;\r\n\r\n    public TurnOnCommand(Light light) {\r\n        _light = light;\r\n    }\r\n\r\n    public void Execute() {\r\n        _light.TurnOn();\r\n    }\r\n}<\/code><\/pre>\n<div class=\"tricky-question\"><strong>Tricky Question:<\/strong> How can you implement undo functionality using the Command pattern?<br \/>\n<strong>Answer:<\/strong> Each command should have an <code>Unexecute()<\/code> method that reverses the <code>Execute()<\/code> operation. Use a stack to manage commands and undo them in reverse order.<\/div>\n","protected":false},"excerpt":{"rendered":"<p>&nbsp; &nbsp; Design Patterns in .NET Core Design patterns are critical for writing scalable and maintainable applications in .NET Core. They allow developers to address common software design challenges and improve code reuse, flexibility, and readability. Below is a breakdown of key patterns used in .NET Core along with tricky interview questions. Creational Design Patterns [&hellip;]<\/p>\n","protected":false},"author":43,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","footnotes":""},"categories":[15,146,24,77,20,121,72],"tags":[153,152,155,154],"class_list":["post-23","post","type-post","status-publish","format-standard","hentry","category-net-core-3-1","category-net-interview-qa","category-c-net","category-important","category-oops","category-system-design","category-unlocking-careers","tag-netcore","tag-designpattern","tag-factory","tag-singleton"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Himanshu Namdeo","author_link":"https:\/\/debuggersspace.com\/author\/admin\/"},"uagb_comment_info":0,"uagb_excerpt":"&nbsp; &nbsp; Design Patterns in .NET Core Design patterns are critical for writing scalable and maintainable applications in .NET Core. They allow developers to address common software design challenges and improve code reuse, flexibility, and readability. Below is a breakdown of key patterns used in .NET Core along with tricky interview questions. Creational Design Patterns&hellip;","_links":{"self":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/23"}],"collection":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/users\/43"}],"replies":[{"embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/comments?post=23"}],"version-history":[{"count":7,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/23\/revisions"}],"predecessor-version":[{"id":930,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/23\/revisions\/930"}],"wp:attachment":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/media?parent=23"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/categories?post=23"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/tags?post=23"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}