tag:blogger.com,1999:blog-15633807483010690042024-03-28T18:49:00.397+05:30Dot Net WorldC# | Asp.Net | MVC | SQL Server | jQuery | Java Script | Angular | .Net CoreManishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.comBlogger192125tag:blogger.com,1999:blog-1563380748301069004.post-58584691179131886732024-03-24T23:52:00.003+05:302024-03-24T23:53:12.542+05:30Observer Design Pattern in C#<p>The Observer Design Pattern is a behavioral design pattern that defines a one-to-many dependency between objects. When one object (the subject) changes its state, all its dependents (observers) are notified and updated automatically. This pattern is widely used in software engineering to establish communication between objects in a loosely coupled manner.</p>
<p>This Design Pattern is widely used for implementing distributed event-handling systems where an object needs to notify other objects about its state changes without knowing who these objects are.</p>
<p>In the Observer Design Pattern, an object (called a Subject) maintains a list of its dependents (called Observers). It notifies them automatically whenever any state changes by calling one of their methods. The Other names of this pattern are Producer/Consumer and Publish/Subscribe.</p>
<h2>Components of Bridge Design Pattern</h2>
<ol><li><strong>Subject</strong>: This is the object that is being observed. It maintains a list of observers and provides methods to attach, detach, and notify observers of state changes.</li>
<li><strong>Observer</strong>: This is the interface that defines the method(s) that the subject will use to notify observers of state changes.</li>
<li><strong>ConcreteSubject</strong>: This is the concrete implementation of the subject. It maintains the state of interest and notifies observers when changes occur.</li>
<li><strong>ConcreteObserver</strong>: This is the concrete implementation of the observer. It registers itself with the subject and implements the update method to react to changes in the subject's state.</li></ol>
<a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#</h2>
<p>Let's demonstrate the Observer Design Pattern using a simple example of a stock market scenario.</p>
<b>Create Subject Interface (ISubject.cs)</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using ObserverPattern.Observer;
namespace ObserverPattern.Subject
{
/// <summary>
/// Subject Interface
/// </summary>
public interface ISubject
{
void Attach(IObserver observer);
void Detach(IObserver observer);
void Notify();
}
}
</pre>
<b>Create Observer Interface (IObserver.cs)</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace ObserverPattern.Observer
{
/// <summary>
/// Observer Interface
/// </summary>
public interface IObserver
{
void Update();
}
}
</pre>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<b>Create Concrete Subject (StockMarket.cs)</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using ObserverPattern.Observer;
namespace ObserverPattern.Subject
{
/// <summary>
/// ConcreteSubject
/// </summary>
public class StockMarket : ISubject
{
private List<IObserver> _observers = new List<IObserver>();
private decimal _stockPrice;
public decimal StockPrice
{
get { return _stockPrice; }
set
{
_stockPrice = value;
// Investors will be notified of the updated price change
Notify();
}
}
public void Attach(IObserver observer)
{
_observers.Add(observer);
}
public void Detach(IObserver observer)
{
_observers.Remove(observer);
}
public void Notify()
{
foreach (var observer in _observers)
{
observer.Update();
}
}
}
}
</pre>
<b>Create Concrete Observer (Investor.cs)</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using ObserverPattern.Subject;
namespace ObserverPattern.Observer
{
/// <summary>
/// ConcreteObserver
/// </summary>
public class Investor : IObserver
{
private string _name;
private ISubject _stockMarket;
public Investor(string name, ISubject stockMarket)
{
_name = name;
_stockMarket = stockMarket;
_stockMarket.Attach(this);
}
public void Update()
{
Console.WriteLine($"{_name} received notification: Stock price changed.");
}
}
}
</pre>
<b>Client Code(Program.cs)</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using ObserverPattern.Observer;
using ObserverPattern.Subject;
StockMarket stockMarket = new StockMarket();
Investor investor1 = new Investor("John", stockMarket);
Investor investor2 = new Investor("Alice", stockMarket);
// Investors will be notified of the price change
stockMarket.StockPrice = 100;
Console.ReadLine();
</pre>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6AbHfnMo59Jq8c2TMzmpkXApnmSs3_sK0cyuq3xZ-c5i28JDvZCgF4QZNkkoR2rWIZ7wkxEc_6CIAVGveK_WpeMBFdYoJ0xegBPMCqzyBKQWGhX5vuDQdeMmIWFHXAXruFUvo1ptFbMlmOgDiaDYC3YSVXyBJNuq2pBkdWNburw1ZdzM0DGeQL-oYNLo/s1600/Screenshot%202024-03-24%20120408.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="" border="0" data-original-height="141" data-original-width="628" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6AbHfnMo59Jq8c2TMzmpkXApnmSs3_sK0cyuq3xZ-c5i28JDvZCgF4QZNkkoR2rWIZ7wkxEc_6CIAVGveK_WpeMBFdYoJ0xegBPMCqzyBKQWGhX5vuDQdeMmIWFHXAXruFUvo1ptFbMlmOgDiaDYC3YSVXyBJNuq2pBkdWNburw1ZdzM0DGeQL-oYNLo/s1600/Screenshot%202024-03-24%20120408.png"/></a></div>
<p style="clear: both;">In this example, <b>StockMarket</b> acts as the subject, while <b>Investor</b> acts as the observer. When the <b>StockPrice</b> changes, all attached investors are notified automatically.</p>
<h2>Benefits of the Observer Design Pattern</h2>
<ol><li><strong>Loose coupling</strong>: The subject and observers are loosely coupled, allowing for easier maintenance and extension of the codebase.</li><li><strong>Reusability</strong>: Since observers are separate from the subject, they can be reused with different subjects.</li><li><strong>Event-driven architecture</strong>: It enables the implementation of event-driven architectures where objects react to changes in state.</li></ol>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-65653919599340558112024-02-15T00:08:00.001+05:302024-02-15T00:08:12.060+05:30Standalone Components in Angular<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="Standalone Components in Angular" border="0" data-original-height="138" data-original-width="138" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png"/></a></div><p>A standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> is a type of component that doesn’t belong to any specific <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> module.Before Angular version 14, when you created a component, you typically had to include it in the declaration array of a module; otherwise, Angular would throw an error during compilation.Standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">components</a> are independent units that can be instantiated and used anywhere within an <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> application, regardless of the module structure. Standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">components</a> can be useful for creating reusable UI elements or utility functions that are not specific to any module.</p>
<p> In this post, we'll explore standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">components</a> in <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> and how to create them with a detailed example.</p>
<h2>Creating a Standalone Component</h2>
<p>First, make sure you're using Angular version 14. To create a component on its own, use the <b>--standalone</b> option with the command <b>ng generate</b> <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a>.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
ng g c component_name --standalone
</pre>
<a name='more'></a>
<p>Above command will generate the standalone component.Below is the example of standalone component-</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { Component } from '@angular/core';
import { CommonModule} from '@angular/common';
@Component({
selector: 'app-example-standalone-component',
standalone: true, // This property should be true for standalone component
imports: [CommonModule],
template: '<h1>Hello, World!</h1>'
})
export class ExampleStandaloneComponent {}
</pre>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>How to Utilize a Standalone Component?</h2>
<p>We can use the standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> in two ways:</p>
<ol>
<li>Within Another Standalone Component
<p>We can use a standalone component inside another standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> by adding it to the <b>imports</b> property of the second component, as shown below.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { Component } from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
selector: 'app-other-standalone-component',
standalone: true,
imports: [CommonModule],
template: '<p>Other standalone component</p>'
})
export class OtherStandAloneComponent {}
</pre>
<p>Now you can use <b>OtherStandAloneComponent</b> <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> on <b>MyStandaloneComponent</b> as below</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { Component } from '@angular/core';
import {CommonModule} from '@angular/common';
import {OtherStandAloneComponent} from 'other-stand-alone/other-stand-alone.component';
@Component({
selector: 'app-my-standalone-component',
standalone: true,
imports: [OtherStandAloneComponent], //import other standalone component here
template: '<h1>Hello, World!</h1><app-other-standalone-component></app-other-standalone-component>'
})
export class MyStandaloneComponent {}
</pre>
</li>
<li>Inside a Module
<p>If you want to use a standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> within another <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> that's part of an <b>NgModule</b>, you can simply add it to the <b>imports</b> array, as shown below.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LandingComponent } from './landing.component';
import {OtherStandAloneComponent} from './other-stand-alone/other-stand-alone.component';
@NgModule({
imports: [CommonModule,OtherStandAloneComponent], // imports standalone compnent
declarations: [LandingComponent]
})
export class LandingModule { }
</pre>
<p>In above , I require a <b>OtherStandAloneComponent</b> in <b>AppComponent</b>, and <b>AppComponent</b> is part of an <b>NgModule</b>. Therefore, I added <b>OtherStandAloneComponent</b> to the imports array.</p>
</li>
</ol>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Bootstrap an Angular Standalone Component</h2>
<p>Bootstraping your <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> is simple. In your <b>main.ts</b> file, replace the old code with the updated code highlighted below in red. Don't forget to specify your standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> in the <b>bootstrapApplication</b> method.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import {enableProdMode} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';
import {StandAloneComponent} from './stand-alone/stand-alone.component';
import {environment} from './environments/environment'
if(environment.Production){
enableProdMode();
}
bootstrapApplication(StandAloneComponent, { //Bootstraping Standalone
providers:[],
})
</pre>
<p>Next, on the <b>index.html</b>, replace <b>app-root</b> with your component.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
<body>
<!--<app-root></app-root>-->
<app-standalone></app-standalone>
</body>
</html>
</pre>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Configuring dependency injection</h2>
<p>When bootstrapping an application, you might need to set up Angular's dependency injection and provide configuration values or services to be used across the app. You can do this by passing them as providers to the <b>bootstrapApplication</b> function.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
bootstrapApplication(StandAloneComponent, {
providers: [
{provide: BACKEND_URL, useValue: 'https://example.com/api'},
// ...
]
});
</pre>
<p>Some existing libraries may depend on <b>NgModules</b> for configuring DI. For instance, Angular’s router utilizes the <b>RouterModule.forRoot()</b> helper to establish routing in an application. You can still use these existing <b>NgModules</b> in <b>bootstrapApplication</b> through the <b>importProvidersFrom</b> utility, as demonstrated below.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
bootstrapApplication(StandAloneComponent, {
providers: [
{provide: BACKEND_URL, useValue: 'https://example.com/api'},
importProvidersFrom(RouterModule.forRoot(APP_ROUTES))
]
});
</pre>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Lazy Loading a Standalone Component</h2>
<p>Any route can implement lazy loading for its routed standalone <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a> by utilizing the <b>loadComponent()</b> function with the import statement.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
export const ROUTES: Route[] = [
{path: 'admin', loadComponent: () => import('./stand-alone/stand-alone.component').then(m => m.StandAloneComponent) },
// ...
];
</pre>
<h2>Conclusion</h2>
<p>Standalone components in Angular provide a way to create reusable UI elements or utility functions that are not tied to any specific module. By creating standalone components, you can promote reusability and maintainability in your Angular applications. In this post, we've learned how to create a standalone component and use it within an Angular application. Experiment with standalone components in your Angular projects to see how they can enhance your development workflow.</p>
<p>Find out more about <a href="https://angular.io/guide/standalone-components" target="_blank">Standalone Component</a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-61315817346965278122024-02-04T18:30:00.003+05:302024-02-04T18:30:00.132+05:30Decorators in Angular<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="Decorators in Angular" border="0" data-original-height="138" data-original-width="138" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png"/></a></div><p>There are several important concepts in <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a>, and <b>Decorators</b> are an important concept to learn when you are working <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a>. <b>Decorators</b> in <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> are a powerful and essential feature used to enhance and modify the behavior of classes, methods, and properties. Through this post we will learn about <b>decorators</b>, its types and how it is being used in real time applications.</p>
<h2>What are Decorators?</h2>
<p><b>Decorators</b> are functions that are invoked with a prefixed <b>@</b> symbol.Basically, a decorator provides configuration metadata that determines how the <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component</a>, class or a function should be processed, instantiated and used at runtime.<b>Decorators</b> are applied to classes, class properties, and class methods using the following syntax:</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
@DecoratorName(arguments)
</pre>
<p><a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> comes with several built-in decorators, and you can also create custom decorators to extend or modify the behavior of your application.</p><a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Types of Decorators</h2>
<p>There are four types of decorators and each type further has its own subset of decorators.</p>
<ol>
<li><b>Class Decorators</b>
<p>This is the initial type of decorator that informs us about a specific class's purpose and helps clarify if the class is a component or a module. <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> has different class decorators, and two commonly used ones are <b>@Component</b> and <b>@NgModule</b>.The below code snippet uses <b>@Component</b>, which is a type of class decorator provided by <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a>.
</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: '<p>This is an example component</p>',
})
export class ExampleComponent {}
</pre>
</li>
<li><b>Property Decorators</b>
<p>Property decorators are employed to enhance specific properties within a class. With a property decorator, we can clearly understand the purpose of using a particular property in a class, such as <a href="https://manish4dotnet.blogspot.com/2023/07/angular-understanding-input-and-output.html" target="_blank">@Input()</a>,<a href="https://manish4dotnet.blogspot.com/2023/07/angular-understanding-input-and-output.html" target="_blank"> @Output</a>, <b>@ReadOnly()</b>, <b>@Override()</b>.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>{{ childData }}</p>',
})
export class ChildComponent {
@Input() childData: string;
@Output() dataChanged = new EventEmitter<string>();
}
</pre>
</li>
<li><b>Method Decorator</b>
<p>Method decorators are used to add functionality to methods within a class. An example of a method decorator is <a href="https://manish4dotnet.blogspot.com/2023/06/angular-hostbinding-and-hostlistener.html" target="_blank">@HostListener</a>.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { Component, HostListener} from '@angular/core';
@Component({
selector: 'app-example',
template: '<p>This is an example component</p>',
})
export class ExampleComponent {
@HostListener('click',['event'])
onHostClick(event:Event) {
// your code
}
} </pre>
</li>
<li><b>Parameter Decorator</b>
<p>Parameter decorators let us decorate parameters in class constructors. A commonly used parameter decorator is <b>@Inject()</b>. It helps inject services into Angular classes.</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
import { Component, Inject} from '@angular/core';
import { MyService} from './my-service';
@Component({
selector: 'app-example',
template: '<p>This is an example component</p>',
})
export class ExampleComponent {
constructor(@Inject(MyService) myService){
console.log(myService);
}
}</pre>
</li>
</ol>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Creating Custom Decorators</h2>
<p>You can also create your own decorators to add custom behavior to your classes. Here's a simple example:</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
function log(message: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log(`${message} ${propertyKey}`);
};
}
class ExampleClass {
@log('Executing')
exampleMethod() {
// Method logic
}
}
const instance = new ExampleClass();
instance.exampleMethod(); // This will log "Executing exampleMethod"
</pre>
<p>In this example, the <b>log</b> decorator is a custom decorator that logs a message when the <b>exampleMethod</b> is executed.</p>
<p><b>Decorators</b> play a crucial role in <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular's architecture</a>, allowing for a clean and modular design of <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">components</a>, <a href="https://manish4dotnet.blogspot.com/2023/07/angular-understanding-directives-in.html" target="_blank">directives</a>, and <b>services</b>. Understanding how to use and create decorators is essential for <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">Angular</a> developers to build scalable and maintainable applications.</p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-12389010094676163882024-01-25T14:30:00.005+05:302024-02-04T06:19:45.272+05:30Bridge Design Pattern in C#<p>The <b><a href="https://manish4dotnet.blogspot.com/2023/08/design-patterns-building-robust-and.html" target="_blank">Bridge Design Pattern</a></b> is a <a href="https://manish4dotnet.blogspot.com/2023/08/design-patterns-building-robust-and.html" target="_blank">structural pattern</a> that separates the abstraction from its implementation so that the two can vary independently.This pattern involves an interface that acts as a bridge between the abstraction class and implementer classes. It is useful in scenarios where an abstraction can have several implementations, and you want to separate the implementation details from the abstraction.</p>
<h2>Purpose of Bridge Pattern</h2>
<ul><li>
Decouple an abstraction from its implementation so that the two can vary independently.</li>
<li>Promote code reusability by allowing the abstraction and implementation to evolve independently.
</li></ul>
<a name='more'></a>
<p>In the <b><a href="https://manish4dotnet.blogspot.com/2023/08/design-patterns-building-robust-and.html" target="_blank">Bridge Design Pattern</a></b>, there are 2 parts. The first part is the <b>Abstraction</b>, and the second part is the <b>Implementation</b>. The <b><a href="https://manish4dotnet.blogspot.com/2023/08/design-patterns-building-robust-and.html" target="_blank">Bridge Design Pattern</a></b> allows both <b>Abstraction</b> and <b>Implementation</b> to be developed independently, and the client code can only access the <b>Abstraction</b> part without being concerned about the Implementation part.</p>
<h2>Components of Bridge Design Pattern:</h2>
<ol><li><strong>Abstraction:</strong> This is an abstract class and containing members that define an abstract business object and its functionality. It contains a reference to an object of type Bridge. It can also act as the base class for other abstractions.</li><li><strong>Refined Abstraction:</strong> This is a class which inherits from the Abstraction class. It extends the interface defined by Abstraction class.</li><li><strong>Implementor(Bridge):</strong> This is an interface which acts as a bridge between the abstraction class and implementer classes and also makes the functionality of implementer class independent from the abstraction class.</li><li><strong>Concrete Implementor:</strong> These are classes which implement the Bridge interface and also provide the implementation details for the associated Abstraction class.</li></ol>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#:</h2>
<p>Let's consider a scenario where we have different shapes, and each shape can be drawn using different drawing engines. We'll implement the Bridge Pattern to achieve the separation of abstraction (shape) and implementation (drawing engine).</p>
<b>Create Bridge Interface(IDrawingEngine.cs):</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace BridgePattern.BridgeInterface
{
/// <summary>
/// Bridge Interface
/// </summary>
public interface IDrawingEngine
{
void DrawCircle(int radius, int x, int y);
void DrawSquare(int side, int x, int y);
}
}
</pre>
<b>Create Concrete Implementors(DrawingEngineA.cs and DrawingEngineB.cs):</b>
<b>DrawingEngineA.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using BridgePattern.BridgeInterface;
namespace BridgePattern.Implementor
{
/// <summary>
/// Concrete Implementors
/// </summary>
public class DrawingEngineA : IDrawingEngine
{
public void DrawCircle(int radius, int x, int y)
{
Console.WriteLine($"Drawing Circle with Engine A: Radius={radius}, X={x}, Y={y}");
}
public void DrawSquare(int side, int x, int y)
{
Console.WriteLine($"Drawing Square with Engine A: Side={side}, X={x}, Y={y}");
}
}
}
</pre>
<b>DrawingEngineB.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using BridgePattern.BridgeInterface;
namespace BridgePattern.Implementor
{
/// <summary>
/// Concrete Implementors
/// </summary>
public class DrawingEngineB : IDrawingEngine
{
public void DrawCircle(int radius, int x, int y)
{
Console.WriteLine($"Drawing Circle with Engine B: Radius={radius}, X={x}, Y={y}");
}
public void DrawSquare(int side, int x, int y)
{
Console.WriteLine($"Drawing Square with Engine B: Side={side}, X={x}, Y={y}");
}
}
}
</pre>
<b>Create Abstraction Class(Shape.cs):</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using BridgePattern.BridgeInterface;
namespace BridgePattern.Abstraction
{
/// <summary>
/// Abstraction Class
/// </summary>
public abstract class Shape
{
protected IDrawingEngine drawingEngine;
protected Shape(IDrawingEngine drawingEngine)
{
this.drawingEngine = drawingEngine;
}
public abstract void Draw();
}
}
</pre>
<b>Create Refined Abstraction(Square.cs and Circle.cs):</b>
<b>Square.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using BridgePattern.Abstraction;
using BridgePattern.BridgeInterface;
namespace BridgePattern.RefinedAbstractions
{
/// <summary>
/// Refined Abstractions
/// </summary>
public class Square : Shape
{
private int side;
private int x;
private int y;
public Square(int side, int x, int y, IDrawingEngine drawingEngine) : base(drawingEngine)
{
this.side = side;
this.x = x;
this.y = y;
}
public override void Draw()
{
drawingEngine.DrawSquare(side, x, y);
}
}
}
</pre>
<b>Circle.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using BridgePattern.Abstraction;
using BridgePattern.BridgeInterface;
namespace BridgePattern.RefinedAbstractions
{
/// <summary>
/// Refined Abstractions
/// </summary>
public class Circle : Shape
{
private int radius;
private int x;
private int y;
public Circle(int radius, int x, int y, IDrawingEngine drawingEngine) : base(drawingEngine)
{
this.radius = radius;
this.x = x;
this.y = y;
}
public override void Draw()
{
drawingEngine.DrawCircle(radius, x, y);
}
}
}
</pre>
<b>Client Code(Program.cs):</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using BridgePattern.Abstraction;
using BridgePattern.BridgeInterface;
using BridgePattern.Implementor;
using BridgePattern.RefinedAbstractions;
IDrawingEngine engineA = new DrawingEngineA();
IDrawingEngine engineB = new DrawingEngineB();
Shape circleA = new Circle(5, 10, 15, engineA);
Shape squareB = new Square(8, 20, 25, engineB);
circleA.Draw();
squareB.Draw();
Console.ReadLine();
</pre>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOfHlX0LDUcHyif5FnA1GklKrWzITf2-dIl-4GaMSgG_2ftMnFP0S223GzwvlesRytMjsCxm_82_iTQh4he6I4-vau3dqn2_VxXhgHWo9RaiCxY6a-V4dhyphenhyphenl2xfFtNjZXh4gAtY6rdfZ3vt2nxi37fqjrbN1OuyOL2kQN-vIyuIhM93IyKr1Ei3hbtEa4/s1600/Screenshot%202024-01-24%20172725.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="" border="0" data-original-height="123" data-original-width="672" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOfHlX0LDUcHyif5FnA1GklKrWzITf2-dIl-4GaMSgG_2ftMnFP0S223GzwvlesRytMjsCxm_82_iTQh4he6I4-vau3dqn2_VxXhgHWo9RaiCxY6a-V4dhyphenhyphenl2xfFtNjZXh4gAtY6rdfZ3vt2nxi37fqjrbN1OuyOL2kQN-vIyuIhM93IyKr1Ei3hbtEa4/s1600/Screenshot%202024-01-24%20172725.png"/></a></div>
<p style="clear: both;">In the above example, <b>Shape</b> is the abstraction, and <b>IDrawingEngine</b> is the implementor(bridge) interface. Concrete implementations of the drawing engines are <b>DrawingEngineA</b> and <b>DrawingEngineB</b>. The <b>Circle</b> and <b>Square</b> classes are refined abstractions that extend the basic interface provided by the Shape class.</p>
<p>By using the <b><a href="https://manish4dotnet.blogspot.com/2023/08/design-patterns-building-robust-and.html" target="_blank">Bridge Design Pattern</a></b>, we can easily switch drawing engines for different shapes without modifying the shape classes, promoting flexibility and maintainability in our code.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-10357783873023524652024-01-21T14:30:00.002+05:302024-02-04T06:21:02.738+05:30Flyweight Design Pattern in C#<p>The <b>Flyweight design pattern</b> is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">structural pattern</a> that focuses on minimizing the memory footprint or computational expenses of an object. It achieves this by sharing as much as possible with related objects, rather than keeping all of the data in each object. This is particularly useful when dealing with a large number of similar objects, as it helps reduce the overall memory consumption and improves performance.</p>
<h2>Purpose of Flyweight Pattern:</h2>
<ul><li>To reduce the number of objects and to conserve memory by sharing objects among multiple contexts.</li><li>To achieve performance improvement by minimizing the overhead of creating and managing large numbers of similar objects.</li></ul>
<a name='more'></a>
<p>The flyweight pattern uses the concepts of intrinsic and extrinsic data.</p>
<p><b>Intrinsic data</b> is held in the properties of the shared flyweight objects. This information is stateless and generally remains unchanged, if any change occurs it would be reflected among all of the objects that reference the flyweight.</p>
<p><b>Extrinsic data</b> is computed on the fly means at runtime and it is held outside of a flyweight object. Hence it can be stateful.</p>
<h2>Components of the Flyweight Pattern:</h2>
<ul><li><strong>Flyweight Interface (IFlyweight):</strong> Declares the interface for flyweight objects.</li><li><strong>ConcreteFlyweight (ConcreteFlyweight):</strong> Implements the Flyweight interface and represents concrete flyweight objects. It stores intrinsic state, which is the state shared with other flyweights.</li><li><strong>UnsharedConcreteFlyweight (UnsharedConcreteFlyweight):</strong> Represents an unshared flyweight object that cannot be shared. It usually contains extrinsic state that must be unique for each object.</li><li><strong>FlyweightFactory:</strong> Manages flyweight objects and ensures that they are shared properly. It often includes methods to retrieve or create flyweight objects.</li></ul>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#</h2>
<p>Here's an example of how you can implement the Flyweight Design Pattern in C#</p>
<p><b>Create the Flyweight Interface:</b> Define an interface or an abstract class for the flyweight objects. This interface should declare methods or properties that allow you to access and manipulate the intrinsic state.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace FlyweightPattern.FlyweightInterface
{
/// <summary>
/// Flyweight interface
/// </summary>
public interface IFont
{
void SetSize(int size);
void SetStyle(string style);
void SetColor(string color);
void Display(string text);
}
}
</pre>
<p><b>Implement Concrete Flyweights:</b> Create concrete classes that implement the flyweight interface. These classes should store and manage the intrinsic state.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FlyweightPattern.FlyweightInterface;
namespace FlyweightPattern.ConcreteFlyweight
{
/// <summary>
/// Concrete Flyweight
/// </summary>
public class ConcreteFont : IFont
{
private int size;
private string style;
private string color;
public void SetSize(int size)
{
this.size = size;
}
public void SetStyle(string style)
{
this.style = style;
}
public void SetColor(string color)
{
this.color = color;
}
public void Display(string text)
{
Console.WriteLine($"Text: '{text}' | Size: {size} | Style: {style} | Color: {color}");
}
}
}
</pre>
<p><b>Create a Flyweight Factory:</b> Implement a factory class responsible for managing and sharing flyweight objects. This factory ensures that each unique combination of intrinsic state is represented by a single flyweight instance.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FlyweightPattern.ConcreteFlyweight;
using FlyweightPattern.FlyweightInterface;
namespace FlyweightPattern.FlyweightFactory
{
/// <summary>
/// Flyweight Factory
/// </summary>
public class FontFactory
{
private Dictionary<string, IFont> fonts = new Dictionary<string, IFont>();
public IFont GetFont(string key)
{
if (!fonts.ContainsKey(key))
{
fonts[key] = new ConcreteFont();
}
return fonts[key];
}
}
}
</pre>
<p><b>Client Code:</b> In your client code, use the flyweight factory to create and share flyweight objects. You can then set their intrinsic state as needed and use them in your application.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FlyweightPattern.FlyweightFactory;
using FlyweightPattern.FlyweightInterface;
FontFactory fontFactory = new FontFactory();
// Create font with different font name
IFont font1 = fontFactory.GetFont("Arial");
IFont font2 = fontFactory.GetFont("Times New Roman");
// Set intrinsic state
font1.SetSize(12);
font1.SetStyle("Regular");
font1.SetColor("Black");
font2.SetSize(14);
font2.SetStyle("Italic");
font2.SetColor("Red");
// Use flyweight objects
font1.Display("Hello, Flyweight Pattern!");
font2.Display("This is a demonstration.");
// Create another font using the same flyweight
IFont font3 = fontFactory.GetFont("Arial");
font3.Display("Same flyweight object");
Console.ReadLine();
</pre>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj7XMjaHOKSSPXig1BHf-17QunrSluDAGRVX8v3AU7A3bNE-ibGRvHhtOdQrGFyOfan8U8CXRpPhFkfA6PkWTOJZULz8Mllf0yoSK8UO5MiWBKmUX2NPPl8c0rvGdCXvnEkvSC5jUPmgxPE95yFbhcLR5sQ5IQHgsBAZwRM8pI-R2dL3fSgKeDMnDdAl_4/s1600/Screenshot%202024-01-20%20201721.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="" border="0" data-original-height="142" data-original-width="896" width="650" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj7XMjaHOKSSPXig1BHf-17QunrSluDAGRVX8v3AU7A3bNE-ibGRvHhtOdQrGFyOfan8U8CXRpPhFkfA6PkWTOJZULz8Mllf0yoSK8UO5MiWBKmUX2NPPl8c0rvGdCXvnEkvSC5jUPmgxPE95yFbhcLR5sQ5IQHgsBAZwRM8pI-R2dL3fSgKeDMnDdAl_4/s1600/Screenshot%202024-01-20%20201721.png"/></a></div>
<p style="clear: both;"><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-83310122183793778382024-01-13T14:30:00.011+05:302024-02-04T06:21:16.865+05:30Proxy Design Pattern in C#<p>The Proxy Design Pattern is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">structural design pattern.</a> that provides a surrogate or placeholder for another object to control access to it.</p>
<p>This pattern comes in handy when we want to add an extra layer of control over the access to an object, such as lazy loading, access control, or logging. In C#, the Proxy Design Pattern is commonly used to create a surrogate object that represents another object.</p>
<p>We can also say that the Proxy is the object the client calls to access the real object behind the scene. Proxy means in place of or on behalf of. That means, In the Proxy Design Pattern, a class represents the functionality of another class.</p>
<h2>Component of Proxy Design pattern</h2>
<ul><li><strong>Subject:</strong> This is an interface that defines the members that will be implemented by the RealSubject and Proxy class so that the Proxy can be used by the client instead of the RealSubject. In our example, it is the ISharedFolder interface.</li><li><strong>RealSubject:</strong> This is a class that we want to use more efficiently by using the proxy class. This class should implement the Subject Interface. In our example, it is the SharedFolder class.</li><a name='more'></a><li><strong>Proxy:</strong> This class holds a reference to the RealSubject class and can access RealSubjecr class members as required. It must implement the same interface as the RealSubject to use the two interchangeably. In our example, it is the SharedFolderProxy class.</li><li><strong>Client:</strong> This Client will be a class, and the client class will use the Proxy class.</li></ul>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#</h2>
<p>Here's an example of how you can implement the Proxy Design Pattern in C#</p>
<p>Let's say that there is a third-party API to get Gold prices in the stock market. These prices are not available for the client application directly. The client application must use a proxy class to get the actual resources, as the main system, that provides this kind of data, cannot allow any third-party to access its database directly.</p>
<p>The main point here will be that, the proxy will fetch the current prices from the actual source, only if the client says yes or no. So our client code will be calling the proxy class and the proxy class will get the price from the actual source and send the current price, back to the client code.</p>
<p>Let's convert the preceding real-world example into technical code.</p>
<div>
<strong>Creating Subject Interface(IPrice.cs)</strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace ProxyPattern.Subject
{
/// <summary>
/// ISubject interface
/// </summary>
public interface IPrice
{
double GetPrice();
}
}
</pre>
<strong>Creating Real Subject(GoldPrice.cs)</strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using ProxyPattern.Subject;
namespace ProxyPattern.RealSubject
{
/// <summary>
/// RealSubject class that implements the IPrice interface
/// </summary>
public class GoldPrice : IPrice
{
int minimum = 999;
int maximum = 9999;
public double GetPrice()
{
Random rnd = new Random();
return rnd.NextDouble() * (maximum - minimum) + minimum;
}
}
}
</pre>
<strong>Creating Proxy Class(Proxy.cs)</strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using ProxyPattern.RealSubject;
using ProxyPattern.Subject;
namespace ProxyPattern.Proxy
{
/// <summary>
/// Proxy Class
/// </summary>
public class Proxy
{
private IPrice _price;
public double GetCurrentGoldPrice(bool isCurrentPrice)
{
if (isCurrentPrice)
{
_price = new GoldPrice();
// Get the actual price
return _price.GetPrice();
}
return 0;
}
}
}
</pre>
<strong>CLient(Program.cs)</strong>
<p>Now we need to write our client code, that will simply create a proxy class instance and call its function.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using ProxyPattern.Proxy;
using ProxyPattern.RealSubject;
// Initiate the proxy class
Proxy _proxy = new Proxy();
// Call the proxy function
var goldPrice = _proxy.GetCurrentGoldPrice(true);
if (goldPrice > 0)
Console.WriteLine("Current Gold price is :{0}", goldPrice);
else
Console.WriteLine("No call to Api");
Console.WriteLine(Environment.NewLine);
goldPrice = _proxy.GetCurrentGoldPrice(false);
if (goldPrice > 0)
Console.WriteLine("Current Gold price is :{0}", goldPrice);
else
Console.WriteLine("No call to Api");
Console.ReadLine();
</pre>
</div>
<p>So as we see here, it is the proxy that is calling the actual resource. Various kinds of business logic like whether the call is from an authenticated source or not, or any other logic can be added to the proxy layer and control the way the resource is being accessed.</p>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJdMLyqcsmp4buDAIVNl0WXXrlCDMcaQAM72dS2Kb9DqztLq2rocOnz4tzdnKMEIYklxxm-_Kc3CvsQ4AicW1UOF7Y7aDooGiRQDGwxgrgKMCECeTGYI3U5P7xCoQSXUu78LfOR8AMceth0gyA0bI1_aIldE9x5gU6UzV-FBopfhHRrO2CvO69YyKK-Ds/s1600/Screenshot%202024-01-13%20173345.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="" border="0" data-original-height="200" data-original-width="558" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJdMLyqcsmp4buDAIVNl0WXXrlCDMcaQAM72dS2Kb9DqztLq2rocOnz4tzdnKMEIYklxxm-_Kc3CvsQ4AicW1UOF7Y7aDooGiRQDGwxgrgKMCECeTGYI3U5P7xCoQSXUu78LfOR8AMceth0gyA0bI1_aIldE9x5gU6UzV-FBopfhHRrO2CvO69YyKK-Ds/s1600/Screenshot%202024-01-13%20173345.png"/></a></div>
<p style="clear: both;">A Proxy Design Pattern has various variations that include:</p>
<ol><li><strong>Virtual Proxy:</strong> A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests or accesses the object.</li><li><strong>Remote Proxy:</strong> A remote proxy provides local representation for an object that resides in a different address space.</li><li><strong>Protection Proxy:</strong> A protection proxy controls access to a sensitive master object. The surrogate object checks that the caller has the access permissions required before forwarding the request.</li></ol>
<p>So depending on our requirements, we may have a combination of one or more of these variations like a protection proxy can be added along with the virtual and remote proxy to authenticate the client making a request for the required data. This was all about the Proxy Design Pattern.</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-89443496805239680592024-01-12T14:30:00.002+05:302024-02-04T06:22:07.702+05:30Composite Design Pattern in C#<p>The Composite Pattern is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">structural design pattern</a> that enables us to treat individual and group objects uniformly by creating a hierarchical (tree-like) structure of objects, where both the composite (groups) objects and leaf (individual) objects share a standard interface.</p>
<p>This pattern lets clients treat individual objects and compositions of objects uniformly. That means the client can access the individual objects or the composition of objects in a uniform manner. It’s useful for representing hierarchical structures such as file systems, UI components, or organizational structures.</p>
<h2>What are Composite and Leaf classes?</h2>
<ol><li>The<strong> Composite Class</strong> — represents a group of objects and can contain other objects (i.e. env_item_collection, env_item_collection_parent, env_root), and</li>
<li >the<strong> Leaf Class</strong> — represents an individual object that cannot contain other objects (i.e. env_item).</li>
</ol>
<a name='more'></a>
<h2>Component of Composite Design Pattern</h2>
<ul><li><strong>Component Interface:</strong> Define an interface or abstract class for implementing the composites and leaf nodes.</li>
<li><strong>Leaf:</strong> Implement the component interface for the leaf nodes with no children.</li>
<li><strong>Composite:</strong> Implement the component interface and also include a collection of components. The composite object can add, remove, and access the child components.</li>
<li><strong>Client Code:</strong> The client works with all elements through the component interface.</li>
</ul>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#</h2>
<p>Here’s an example in C# to illustrate the Composite Design Pattern.Let's consider a scenario where we have a company's organizational structure that includes employees and groups of employees.</p>
<div>
<b>Step1: Creating Component Interface(IEmployee.cs)</b>
<p>Create an interface named <b>IEmployee.cs</b> and copy and paste the following code.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace CompositeDesignPattern.ComponentInterface
{
/// <summary>
/// Component - The base interface or abstract class for all the objects in the composition
/// </summary>
public interface IEmployee
{
void DisplayDetails();
}
}
</pre>
<b>Step2: Creating Leaf Class(Employee.cs)</b>
<p>The Leaf class represents the end objects, i.e., the object that does the actual work. A leaf can’t have any children. So, create a class file with the name <b>Employee.cs</b> and copy and paste the following code. </p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using CompositeDesignPattern.ComponentInterface;
namespace CompositeDesignPattern.Leaf
{
/// <summary>
/// Leaf - Represents individual employees
/// </summary>
public class Employee : IEmployee
{
private readonly string _name;
private readonly string _position;
public Employee(string name, string position)
{
_name = name;
_position = position;
}
public void DisplayDetails()
{
Console.WriteLine($"Employee: {_name}, Position: {_position}");
}
}
}
</pre>
<b>Step3: Creating Composite Class(EmployeeGroup.cs)</b>
<p>The Composite class represents the composite components that have children. The Composite objects delegate the actual work to their children and then combine the results. So, create a class file named <b>EmployeeGroup.cs</b> and copy and paste the following code.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using CompositeDesignPattern.ComponentInterface;
namespace CompositeDesignPattern.Composite
{
/// <summary>
/// Composite - Represents a group of employees
/// </summary>
public class EmployeeGroup : IEmployee
{
private readonly List<IEmployee> _employees = new List<IEmployee>();
public void AddEmployee(IEmployee employee)
{
_employees.Add(employee);
}
public void DisplayDetails()
{
foreach (var employee in _employees)
{
employee.DisplayDetails();
}
}
}
}
</pre>
<b>Step4: Client(Program.cs)</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using CompositeDesignPattern.Composite;
using CompositeDesignPattern.Leaf;
// Create individual employees
var employee1 = new Employee("Alice", "Manager");
var employee2 = new Employee("Bob", "Developer");
var employee3 = new Employee("Charlie", "Designer");
// Create a group and add employees to it
var group1 = new EmployeeGroup();
group1.AddEmployee(employee1);
group1.AddEmployee(employee2);
var group2 = new EmployeeGroup();
group2.AddEmployee(employee3);
// Create a larger group and add the previously created groups to it
var largerGroup = new EmployeeGroup();
largerGroup.AddEmployee(group1);
largerGroup.AddEmployee(group2);
// Display details of the larger group, which recursively displays all employees
largerGroup.DisplayDetails();
Console.ReadKey();
</pre>
</div>
<p>In the above example, the <b>IEmployee</b> interface is the component that both the <b>leaf (Employee)</b> and <b>composite (EmployeeGroup)</b> classes implement. <b>Employee</b> represents individual employees, while EmployeeGroup represents a group of employees. The EmployeeGroup class can contain either individual <b>Employee</b> objects or other <b>EmployeeGroup</b> objects, forming a tree-like structure.</p>
<p>When <b>DisplayDetails()</b> is called on the larger group, it traverses through the structure, displaying details of all individual employees within the groups.</p>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixqwf4KB396zXjskA0x4ydvePexc4itULOS2hNJvtxenlU42VSCpWtqzn4aHqbPPWYkaDI7J-L_GRfDh1K8Dan5amVwXR1Js8q9uK_BhBEDzYv-XR4qJ7WIERnaiOgjkoIO34kcegg6gbrL6kBuYP7nt2jfh-liSfFj9cb4MGNay7rBpT__uE1riNOQGE/s1600/Screenshot%202024-01-11%20221347.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="" border="0" data-original-height="170" data-original-width="585" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixqwf4KB396zXjskA0x4ydvePexc4itULOS2hNJvtxenlU42VSCpWtqzn4aHqbPPWYkaDI7J-L_GRfDh1K8Dan5amVwXR1Js8q9uK_BhBEDzYv-XR4qJ7WIERnaiOgjkoIO34kcegg6gbrL6kBuYP7nt2jfh-liSfFj9cb4MGNay7rBpT__uE1riNOQGE/s1600/Screenshot%202024-01-11%20221347.png"/></a></div>
<p style="clear: both;">This pattern allows treating individual objects and compositions of objects uniformly, making it easier to work with complex tree structures.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-14420856639686324032024-01-08T03:30:00.002+05:302024-02-04T06:22:24.464+05:30Facade Design Pattern in C#<p>Facade is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">structural design pattern</a> that provides a simplified interface to a library, a framework, or any other complex set of classes.It helps encapsulate the complexity of multiple subsystems into a single unified interface.</p>
<p>In software terms, Facade pattern hides the complexities of the systems and provides a simple interface to the clients.</p>
<p>This pattern involves one wrapper class which contains a set of methods available for the client. This pattern is particularly used when a system is very complex or difficult to understand and when the system has multiple subsystems.</p>
<h2>Component of Facade Design Pattern</h2>
<ul>
<li><strong>Complex System: </strong>A library of subsystems.</li>
<li><strong>Subsystems:</strong> These are classes within a complex system and offer detailed operations.</li>
<li><strong>Façade: </strong>This is a wrapper class which wrapper class which contains a set of members which are required by the client.</li>
<li><strong>Client: </strong>This is a class which calls the high-level operations in the Façade.</li>
</ul><a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#</h2>
<p>Here's an example demonstrating the Facade Pattern in C#.Let's consider a multimedia system with several complex subsystems like the AudioPlayer, VideoPlayer, and DisplaySystem.</p>
<ol>
<li><strong>Subsystems: </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace FacadePattern.Subsystem
{
/// <summary>
/// Subsystem 1: AudioPlayer
/// </summary>
public class AudioPlayer
{
public void PlayAudio(string audioFile)
{
Console.WriteLine("Playing audio: " + audioFile);
}
}
}
</pre>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace FacadePattern.Subsystem
{
/// <summary>
/// Subsystem 2: VideoPlayer
/// </summary>
public class VideoPlayer
{
public void PlayVideo(string videoFile)
{
Console.WriteLine("Playing video: " + videoFile);
}
}
}
</pre>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace FacadePattern.Subsystem
{
/// <summary>
/// Subsystem 3: DisplaySystem
/// </summary>
public class DisplaySystem
{
public void Display(string displayContent)
{
Console.WriteLine("Displaying: " + displayContent);
}
}
}
</pre>
</li>
<li><strong>Facade Class(MultimediaFacade.cs): </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FacadePattern.Subsystem;
namespace FacadePattern.Facade
{
/// <summary>
/// Facade: MultimediaFacade
/// </summary>
public class MultimediaFacade
{
private AudioPlayer audioPlayer;
private VideoPlayer videoPlayer;
private DisplaySystem displaySystem;
public MultimediaFacade()
{
audioPlayer = new AudioPlayer();
videoPlayer = new VideoPlayer();
displaySystem = new DisplaySystem();
}
// Facade methods that provide a simpler interface
public void PlayMusic(string audioFile)
{
audioPlayer.PlayAudio(audioFile);
}
public void PlayMovie(string videoFile)
{
videoPlayer.PlayVideo(videoFile);
}
public void DisplayContent(string content)
{
displaySystem.Display(content);
}
}
} </pre>
</li>
<li><strong>Client: </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FacadePattern.Facade;
MultimediaFacade multimedia = new MultimediaFacade();
// Using the facade to simplify interaction
multimedia.PlayMusic("song.mp3");
multimedia.PlayMovie("movie.mp4");
multimedia.DisplayContent("Welcome to our multimedia system!");
Console.ReadKey();
</pre>
</li>
</ol>
<p>In this example, the <b>MultimediaFacade</b> acts as a simplified interface to the complex subsystems <b>(AudioPlayer, VideoPlayer, DisplaySystem)</b>. The client code interacts only with the facade, which in turn delegates the tasks to the appropriate subsystems.</p>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8RABDZLTbZXIxaZwE1dATpBUALspOuoK93b8xhAuSO37R3jTCXOGxPyax6skqPLTKxIhe_KFuZGUWI9PVlGXD5LfoYezKFZpfKCU3QBRvarGu_DPjdR6SmCp0czpFUiqdd7OQVUPxpJIRrQafj7oRdUXiP_QhtWBhiz_9mHNEP_1zs2qo_5Af_lDKZW0/s1600/Screenshot%202024-01-07%20112359.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="" border="0" data-original-height="171" data-original-width="672" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8RABDZLTbZXIxaZwE1dATpBUALspOuoK93b8xhAuSO37R3jTCXOGxPyax6skqPLTKxIhe_KFuZGUWI9PVlGXD5LfoYezKFZpfKCU3QBRvarGu_DPjdR6SmCp0czpFUiqdd7OQVUPxpJIRrQafj7oRdUXiP_QhtWBhiz_9mHNEP_1zs2qo_5Af_lDKZW0/s1600/Screenshot%202024-01-07%20112359.png"/></a></div>
<h2 style="clear: both;">When to use this pattern</h2>
<p style="clear: both;">
Use this pattern to simplify the problem when there are multiple complex subsystems and interacting with them individually is really difficult/cumbersome.
</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-46626059076957050132024-01-02T14:30:00.002+05:302024-02-04T06:22:36.192+05:30Decorator Design Pattern in C#<p>The <b>Decorator Design Pattern</b> is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">structural pattern</a> in software development that allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class.</p>
<p>The idea of the <b>Decorator Pattern</b> is to wrap an existing class, add other functionality to it, then expose the same interface to the outside world. Because of this our decorator exactly looks like the original class to the people who are using it.</p>
<p>It is used to extend or alter the functionality at runtime. It does this by wrapping them in an object of the decorator class without modifying the original object. So it can be called a wrapper pattern.</p>
<h2>Components of Decorator Design Pattern</h2>
<ul>
<li><strong>Component: </strong>It defines the interface of the actual object that needs functionality to be added dynamically to the ConcreteComponents.</li>
<li><strong>ConcreteComponent:</strong> The actual object in which the functionalities could be added dynamically.</li>
<li><strong>Decorator: </strong>This defines the interface for all the dynamic functionalities that can be added to the ConcreteComponent.</li>
<li><strong>ConcreteDecorator: </strong>All the functionalities that can be added to the ConcreteComponent. Each needed functionality will be one ConcreteDecorator class. </li>
</ul><a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#</h2>
<p>In C#, let's illustrate the <b>Decorator Pattern</b> with an example involving a beverage system, where we have a base <b>Beverage</b> class representing different types of drinks.</p>
<ol>
<li><strong>Component(IBeverage.cs): </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace DecoratorPattern.Component
{
/// <summary>
/// Interface for beverage
/// </summary>
public interface IBeverage
{
string GetDescription();
double Cost();
}
}
</pre>
</li>
<li><strong>Concrete Component(Coffee.cs): </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace DecoratorPattern.Component
{
/// <summary>
/// Concrete component representing a basic beverag
/// </summary>
public class Coffee : IBeverage
{
public string GetDescription()
{
return "Coffee";
}
public double Cost()
{
return 5.0;
}
}
}
</pre>
</li>
<li><strong>Decorator(BeverageBaseDecorator.cs): </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using DecoratorPattern.Component;
namespace DecoratorPattern.Decorator
{
/// <summary>
/// Decorator base class
/// </summary>
public abstract class BeverageBaseDecorator : IBeverage
{
protected IBeverage _beverage;
public BeverageBaseDecorator(IBeverage beverage)
{
_beverage = beverage;
}
public virtual string GetDescription()
{
return _beverage.GetDescription();
}
public virtual double Cost()
{
return _beverage.Cost();
}
}
}
</pre>
</li>
<li><strong>ConcreteDecorator(MilkDecorator.cs and SugarDecorator.cs): </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using DecoratorPattern.Component;
namespace DecoratorPattern.Decorator
{
/// <summary>
/// Concrete decorator adding milk to the beverage
/// </summary>
public class MilkDecorator : BeverageBaseDecorator
{
public MilkDecorator(IBeverage beverage) : base(beverage)
{
}
public override string GetDescription()
{
return $"{_beverage.GetDescription()}, Milk";
}
public override double Cost()
{
return _beverage.Cost() + 0.5; // Milk costs 0.5
}
}
}
</pre>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using DecoratorPattern.Component;
namespace DecoratorPattern.Decorator
{
/// <summary>
/// Concrete decorator adding sugar to the beverage
/// </summary>
public class SugarDecorator : BeverageBaseDecorator
{
public SugarDecorator(IBeverage beverage) : base(beverage)
{
}
public override string GetDescription()
{
return $"{_beverage.GetDescription()}, Sugar";
}
public override double Cost()
{
return _beverage.Cost() + 0.2; // Sugar costs 0.2
}
}
}
</pre>
</li>
<li><strong>Client: </strong>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
// Create a base coffee
using DecoratorPattern.Component;
using DecoratorPattern.Decorator;
IBeverage coffee = new Coffee();
// Decorate the coffee with milk
coffee = new MilkDecorator(coffee);
// Decorate the coffee further with sugar
coffee = new SugarDecorator(coffee);
// Output the description and cost of the final beverage
Console.WriteLine($"Description: {coffee.GetDescription()}");
Console.WriteLine($"Cost: ${coffee.Cost()}");
Console.ReadLine();
</pre>
</li>
</ol>
<p>This example demonstrates how you can dynamically add responsibilities to objects at runtime using the Decorator Pattern in C#. Each decorator transparently adds its own behavior to the component it decorates without affecting the behavior of other objects from the same class.</p>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgq9xmA9mo9ADHgps6vPlY-UZ8yi69xi3oQlmMCCnCV7uwApsS4Tx1XsPnE9UoWs-lzeD6jccp3DLkT7pwSE7BB8ANfsRChX30pLcb082oTRXGHWlHqORMkoQPshtxEgDsjTivU5WUMbaqYrd2TjvSgMfGv161rdzrWmRu8WQHF1LXQrqVZ0wuZI-To3sc/s1600/Screenshot%202023-12-31%20142054.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="decorator design pattern" border="0" data-original-height="136" data-original-width="557" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgq9xmA9mo9ADHgps6vPlY-UZ8yi69xi3oQlmMCCnCV7uwApsS4Tx1XsPnE9UoWs-lzeD6jccp3DLkT7pwSE7BB8ANfsRChX30pLcb082oTRXGHWlHqORMkoQPshtxEgDsjTivU5WUMbaqYrd2TjvSgMfGv161rdzrWmRu8WQHF1LXQrqVZ0wuZI-To3sc/s1600/Screenshot%202023-12-31%20142054.png"/></a></div>
<h2 style="clear: both;">Advantages of Decorator Pattern</h2>
<ol>
<li>Adds functionality to existing objects dynamically
</li>
<li>Alternative to sub classing
</li>
<li>Flexible design
</li>
<li>Supports Open Closed Principle </li>
</ol>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-13928467332605696532023-12-29T14:30:00.002+05:302024-02-04T06:22:50.775+05:30Adapter Design Pattern in C#<p>The <b>Adapter Design Pattern</b> is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">structural pattern</a> that allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces, enabling them to collaborate seamlessly without modifying their existing code.The adapter plays the role of converter or translator.</p>
<p>This <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">pattern</a> is particularly useful when integrating new components or systems that have different interfaces from the ones already in use.</p>
<p>To handle the incompatibility, we use different approaches, and based on that, we can classify the Adapter Pattern into 2 parts.</p>
<ul>
<li>Object Adapter Pattern</li>
<li>Class Adapter Pattern</li>
</ul>
<a name='more'></a>
<h2>Object Adapter Design Pattern</h2>
<p>In Object Adapter Pattern, Incompatibility is handled by creating the object.</p>
<h2>Class Adapter Design Pattern</h2>
<p>Class Adapter Design Pattern Incompatibility is handled by inheritance.</p>
<h2>Components of Adapter Design Pattern</h2>
<ul><li><b>Target:</b> The interface that is expected by the client code.</li>
<li><b>Adaptee:</b> The existing class or interface that needs to be integrated into the system but has an incompatible interface with the Target.</li>
<li><b>Adapter:</b> The class that bridges the gap between Target and Adaptee by implementing the Target interface and internally using the Adaptee.</li>
</ul>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Example in C#:</h2>
<p>Let's consider a scenario where we have an <b>OldPrinter</b> class with a method <b>PrintOld()</b>, and we want to integrate it into a system that expects a different interface, say <b>INewPrinter</b> with <b>PrintNew()</b> method.In this example, the <b>PrinterAdapter</b> class implements the <b>INewPrinter</b> interface by internally using the <b>OldPrinter</b> class.</p>
<ol>
<li><b>Adaptee:</b> Existing class with an incompatible interface.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AdapterPattern.Adaptee
{
public class OldPrinter
{
public void PrintOld()
{
Console.WriteLine("Printing with the old printer.");
}
}
}
</pre>
</li>
<li><b>Target:</b> New interface expected by the client.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AdapterPattern.Target
{
public interface INewPrinter
{
void PrintNew();
}
}
</pre>
</li>
<li><b>Adapter:</b> Bridges the gap between OldPrinter and INewPrinter.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using AdapterPattern.Adaptee;
using AdapterPattern.Target;
namespace AdapterPattern.Adapter
{
// Adapter: Bridges the gap between OldPrinter and INewPrinter
public class PrinterAdapter : INewPrinter
{
private readonly OldPrinter oldPrinter;
public PrinterAdapter(OldPrinter oldPrinter)
{
this.oldPrinter = oldPrinter;
}
public void PrintNew()
{
// Call the old printer's method through the adapter
oldPrinter.PrintOld();
}
}
}
</pre>
</li>
<li><b>Client:</b> The client code interacts with the <b>INewPrinter</b> interface, which internally calls the methods of the <b>OldPrinter</b> class through the adapter..
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using AdapterPattern.Adaptee;
using AdapterPattern.Adapter;
using AdapterPattern.Target;
OldPrinter oldPrinter = new OldPrinter();
// Adapter to use OldPrinter as a NewPrinter
INewPrinter adaptedPrinter = new PrinterAdapter(oldPrinter);
// Using the NewPrinter interface
adaptedPrinter.PrintNew();
Console.ReadLine();
</pre>
</li>
</ol>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1_9Srp80a6yZr0ithwmLrAiijBeWLb5dHdOByd5F2Nh55cJ8ak-lx2RJb2E0AifOCoxpLCVp2w_3MFQ7wB_M4pxU-9nJ-ZwsXKbwYhtsiBNtJNc2LhXoczuBr6vfswxeJVUGk83ZnfohwD9MIY98zpzQ22Wtsfa5nOSVeDvtINunQtXDDFDUryKrfCIw/s1600/Screenshot%202023-12-24%20220951.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="adapter design pattern example" border="0" data-original-height="110" data-original-width="383" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1_9Srp80a6yZr0ithwmLrAiijBeWLb5dHdOByd5F2Nh55cJ8ak-lx2RJb2E0AifOCoxpLCVp2w_3MFQ7wB_M4pxU-9nJ-ZwsXKbwYhtsiBNtJNc2LhXoczuBr6vfswxeJVUGk83ZnfohwD9MIY98zpzQ22Wtsfa5nOSVeDvtINunQtXDDFDUryKrfCIw/s1600/Screenshot%202023-12-24%20220951.png"/></a></div>
<h2 style="clear: both;">Advantages of the Adapter Pattern:</h2>
<ul><li><b>Interoperability</b>: Allows integration of incompatible interfaces.</li><li><b>Reusability</b>: Existing classes can be used in new systems without modifying their code.</li><li><b>Maintainability</b>: Helps in keeping existing code intact while adapting to new requirements.</li></ul>
<p>The <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">Adapter Design Pattern</a> is a powerful tool for integrating diverse components or systems with different interfaces, promoting flexibility and maintainability in software <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">design</a>.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-43917318545773509372023-12-28T14:30:00.001+05:302023-12-29T01:45:04.882+05:30Response Caching in .NET Core with Example<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="Response Caching in .NET Core" border="0" data-original-height="174" data-original-width="200" height="150" width="150" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png"/></a></div><p><a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">Caching</a> responses is a powerful technique to improve the performance and scalability of web applications. In <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a>, response caching is a feature that helps store the output of an action method for a specified duration, allowing subsequent requests to retrieve the cached result instead of re-executing the action.</p>
<h2 style="clear: both;padding-top:10px">How to Implement Response Caching in .NET Core?</h2>
<ol>
<li><b>Enable Response Caching in Startup.cs</b>
<p>In the <b>ConfigureServices</b> method of <b>Startup.cs</b>, enable response caching by adding the required services.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
// Other configurations...
}
</pre>
</li><a name='more'></a>
<li><b>Use Response Caching in Controller Actions</b>
<p>To cache the response of an action method, decorate the action with <b>[ResponseCache]</b> attribute and specify cache-related settings.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
[ResponseCache(Duration = 60)] // Cache for 60 seconds
public IActionResult MyAction()
{
// Your action logic
return View();
}
</pre>
</li>
<li><b>Customizing Cache Settings</b>
<p>You can customize caching behavior using various parameters in the <b>[ResponseCache]</b> attribute.</p>
<ul><li><b>Duration</b>: Specifies the time duration in seconds for which the response should be cached.</li><li><b>Location</b>: Determines where the response can be cached (Any, Client, or Server).</li><li><b>NoStore</b>: If set to <b>true</b>, response won’t be stored in the cache.</li><li><b>VaryByHeader</b>: Allows caching variations based on request headers.</li><li><b>VaryByQueryKeys</b>: Enables caching variations based on query parameters.</li></ul>
</li>
<li><b>Applying Cache Profile (Optional)</b>
<p>You can define caching settings globally using a cache profile in <b>Startup.cs</b> and apply it to multiple actions.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
services.AddMvc(options =>
{
options.CacheProfiles.Add("CustomCacheProfile", new CacheProfile
{
Duration = 120,
Location = ResponseCacheLocation.Any
// Other settings...
});
});
}
</pre>
<p>Then, apply this profile to actions:</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
[ResponseCache(CacheProfileName = "CustomCacheProfile")]
public IActionResult MyCachedAction()
{
// Action logic
return View();
}
</pre>
</li>
</ol>
<h2>Benefits of Response Caching</h2>
<ol><li><strong>Improved Performance</strong>: Reduces server load by serving cached responses.</li><li><strong>Faster User Experience</strong>: Users receive quicker responses, enhancing their experience.</li><li><strong>Reduced Network Traffic</strong>: Cached responses minimize data transfer between the client and server.</li></ol>
<h2>Considerations</h2>
<ul><li><strong>Cache Invalidation</strong>: Ensure cached data is updated or invalidated appropriately when changes occur.</li><li><strong>Sensitive Data</strong>: Avoid caching sensitive information or use cache profiles carefully.</li><li><strong>Monitoring</strong>: Monitor cache usage to optimize caching strategies.</li></ul>
<p>Response caching is a powerful tool, but like any <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> mechanism, it requires thoughtful implementation considering factors like data volatility, user session handling, and security. When used judiciously, it significantly enhances application performance.</p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-80719580820571164172023-12-27T14:30:00.009+05:302023-12-29T01:44:38.239+05:30Distributed Caching in .NET Core with Example<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="Distributed Caching in .NET Core" border="0" data-original-height="174" data-original-width="200" height="150" width="150" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png"/></a></div>
<p>In <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a>, managing <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> efficiently can significantly enhance the performance of applications.<b>IDistributedCache</b> interface provides a unified approach to caching data in a distributed environment, allowing seamless integration with various caching systems like Redis, SQL Server, or in-memory cache.</p>
<h2>What is IDistributedCache?</h2>
<p><b>IDistributedCache</b> is an abstraction in <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> that enables applications to interact with distributed cache stores. It offers methods to set, retrieve, and remove cached data in a consistent manner across different cache providers.</p>
<a name='more'></a>
<h2>Implementation Example</h2>
<p>Let's delve into a simple example of how to use <b>IDistributedCache</b> in a <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> application.</p>
<ol>
<li><b>Setting up the Cache Service</b>
<p>Start by configuring the cache service in the <b>Startup.cs</b> file within the <b>ConfigureServices</b> method.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
services.AddDistributedRedisCache(options =>
{
options.Configuration = Configuration.GetConnectionString("RedisCache");
options.InstanceName = "SampleInstance";
});
</pre>
<p>In this example, <b>Redis cache</b> is used. Ensure you've installed the <b>Microsoft.Extensions.Caching.Redis</b> package via NuGet.</p>
</li>
<li><b>Injecting IDistributedCache</b>
<p>Inject <b>IDistributedCache</b> into your controller or service.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
private readonly IDistributedCache _cache;
public SampleController(IDistributedCache cache)
{
_cache = cache;
}
</pre>
</li>
<li><b>Using the Cache</b>
<p>Utilize the cache to store and retrieve data.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
// Storing data in cache
byte[] data = Encoding.UTF8.GetBytes("Your data to cache");
var cacheEntryOptions = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(10)); // Set cache expiration
await _cache.SetAsync("CacheKey", data, cacheEntryOptions);
// Retrieving data from cache
var cachedData = await _cache.GetAsync("CacheKey");
if (cachedData != null)
{
string cachedString = Encoding.UTF8.GetString(cachedData);
// Make use of the cachedString
}
</pre>
</li>
<li><b>Handling Cache Expiration and Eviction</b>
<p>The example demonstrates setting a sliding expiration for cached data. You can also use absolute expiration or eviction policies based on your application's requirements.</p>
</li>
<li><b>Error Handling</b>
<p>When using distributed <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a>, handle exceptions that might occur due to network issues or other transient errors while interacting with the cache.</p>
</li>
</ol>
<p>By utilizing <b>IDistributedCache</b>, applications gain the flexibility to switch between different <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> systems without altering the caching logic significantly. This promotes scalability and performance optimization.</p>
<p>Understanding and implementing <b>IDistributedCache</b> in your <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> applications can significantly enhance performance, reduce database load, and improve overall user experience.</p>
<p>Remember, <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> strategies should be designed based on the specific needs and nature of your application's data access patterns. Start implementing <b>IDistributedCache</b> today to unlock the performance benefits it offers in your <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> applications</p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-46769030626284557862023-12-25T14:30:00.002+05:302024-02-04T06:24:47.012+05:30IMemoryCache in .NET Core with Example<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="IMemoryCache in .NET Core" border="0" data-original-height="174" data-original-width="200" height="150" width="150" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png"/></a></div><p>In <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a>, managing <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> efficiently can significantly enhance the performance of applications. The <b>IMemoryCache</b> interface plays a pivotal role in <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> data in memory, providing a simple and effective way to store and retrieve cached data within your applications. This post aims to provide an in-depth understanding of <b>IMemoryCache</b> and its implementation with illustrative examples.</p>
<h2>What is IMemoryCache?</h2>
<p><b>IMemoryCache</b> is an interface provided by the <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> framework, designed to <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">cache</a> data in memory within an application. It enables developers to temporarily store frequently accessed data, reducing the need to fetch it from the original source repeatedly.</p><a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Implementation Example</h2>
<p>Let's explore a basic example of how to use <b>IMemoryCache</b> in a <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> application.</p>
<ol>
<li><b>Step1:Adding the required namespace</b>
<p>Firstly, ensure you have the necessary namespace imported at the top of your file:</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using Microsoft.Extensions.Caching.Memory;
</pre>
</li>
<li><b>Step2:Setting up the Cache</b>
<p>In your application, you can configure the <b>IMemoryCache</b> instance in the <b>ConfigureServices</b> method of the <b>Startup.cs</b> file:</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
// Other service configurations...
}
</pre>
</li>
<li><b>Step 3: Caching Data</b>
<p>Now, let's cache data using <b>IMemoryCache</b></p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
private readonly IMemoryCache _memoryCache;
public ExampleService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public void CacheData(string key, object data)
{
// Store data in the cache with an expiration time
_memoryCache.Set(key, data, TimeSpan.FromMinutes(10));
}
public object GetCachedData(string key)
{
// Retrieve data from the cache
if (_memoryCache.TryGetValue(key, out object cachedData))
{
return cachedData;
}
return null;
}
</pre>
<p>In this example, <b>CacheData</b> method allows you to store data in the cache with a specific expiration time, while <b>GetCachedData</b> retrieves the cached data based on the provided key.</p>
</li>
<li><b>Step 4: Utilizing Cached Data</b>
<p>You can now utilize the cached data in your application, fetching it from the cache instead of generating or retrieving it again from the original source.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
// Fetch data from cache or source
var cachedResult = GetCachedData("myCachedDataKey");
if (cachedResult == null)
{
// If data doesn't exist in the cache, fetch from the source and cache it
var dataFromSource = FetchDataFromSource();
CacheData("myCachedDataKey", dataFromSource);
cachedResult = dataFromSource;
}
// Use cachedResult...
</pre>
</li>
</ol>
<p><b>IMemoryCache</b> in <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> provides a powerful way to manage in-memory <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a>, optimizing the performance of applications by reducing resource-intensive operations. By efficiently <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> data, you can enhance the responsiveness and scalability of your <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> applications.</p>
<p>This post covered the basics of <b>IMemoryCache</b> along with a practical implementation example to get you started. Experiment with <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">caching</a> strategies and leverage the capabilities of <b>IMemoryCache</b> to optimize your applications effectively.</p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-34077391085088420932023-12-18T07:35:00.003+05:302024-02-04T06:24:18.492+05:30What is the difference between IMemoryCache and IDistributedCache?<p><b>IMemoryCache</b> and <b>IDistributedCache</b> are both interfaces in <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">ASP.NET Core</a> used for caching data, but they differ in terms of scope and storage.</p>
<h2 style="clear: both;">IMemoryCache</h2>
<ul>
<li><b>Scope:</b> Local to the application instance.</li>
<li><b>Storage:</b> Caches data in the memory of the local application.</li>
<li><b>Usage:</b> Ideal for scenarios where data needs to be cached within the same application instance and doesn't need to be shared across multiple instances or servers.</li>
<li><b>Pros:</b> Faster access since it operates within the application's memory.</li>
<li><b>Cons:</b> Limited to a single instance and doesn't support sharing data between different instances or servers.</li>
</ul>
<a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>IDistributedCache</h2>
<ul>
<li><b>Scope:</b> Allows caching to be shared across multiple instances or servers (distributed environment).</li>
<li><b>Storage:</b> Can use various distributed storage mechanisms like Redis, SQL Server, or other external stores to cache data.</li>
<li><b>Usage:</b> Useful for scenarios where data needs to be shared among multiple instances of the application or across a server farm.</li>
<li><b>Pros:</b> Supports scalability and sharing of cached data across multiple instances or servers.</li>
<li><b>Cons:</b> Might have slightly slower access compared to in-memory caching due to the network or external storage latency.</li>
</ul>
<p>In summary, <b>IMemoryCache</b> is local to the application and is suitable for single-instance scenarios, while <b>DistributedCache</b> is designed for distributed applications where caching needs to be shared across multiple instances or servers.</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com2tag:blogger.com,1999:blog-1563380748301069004.post-70461230928344192512023-12-17T09:25:00.005+05:302024-02-04T06:23:25.899+05:30What is CacheEntryOptions in .NET Core
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="CacheEntryOptions in .NET Core" border="0" data-original-height="174" data-original-width="200" height="150" width="150" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png"/></a></div><p><a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">Caching</a> plays a crucial role in enhancing the performance and scalability of applications. In <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a>, MemoryCache class enables storing frequently accessed data in memory, facilitating quick retrieval. To tailor <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">cached</a> item behavior, developers can utilize <b>CacheEntryOptions</b>. This post delves into <b>CacheEntryOptions</b> and its role in customizing caching behavior in <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET core</a> applications.</p>
<br/><br/>
<h2>What are CacheEntryOptions?</h2>
<p><b>CacheEntryOptions</b>, found in the <b>Microsoft.Extensions.Caching.Memory</b> namespace, empowers developers to configure various settings related to cached items in <a href="https://manish4dotnet.blogspot.com/2023/08/understanding-caching-in-net-core-api.html" target="_blank">MemoryCache</a>. These options allow control over properties such as expiration time, priority, and post-eviction callbacks for cached items.</p>
<h2>Key Properties of CacheEntryOptions</h2>
<ol>
<li><b>AbsoluteExpiration and AbsoluteExpirationRelativeToNow:</b>These properties allow specifying when a cached item should expire, either at an absolute time or after a certain duration from its addition to the cache.</li>
<li><b>SlidingExpiration:</b>SlidingExpiration enables defining a time window after which the cached item expires if not accessed. Each access to the item resets the sliding window.</li>
<li><b>Priority:</b>CacheEntryOptions lets you set the priority of cached items, affecting their likelihood of being removed from the cache upon expiration or when the cache needs space for new items.</li>
<a name='more'></a>
<li><b>Size:</b>With CacheEntryOptions, it's possible to set the size of cached items, which proves useful in memory-limited caches for controlling item sizes and preventing excessive memory usage.</li>
<li><b>PostEvictionCallbacks:</b>Post-eviction callbacks allow registering a delegate that executes when a cached item is evicted from the cache. This is beneficial for performing cleanup actions or logging when an item is removed.</li>
</ol>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Using CacheEntryOptions in <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a>:</h2>
<p>To use <b>CacheEntryOptions</b>, create an instance of this class and set the desired properties. Then, pass the <b>CacheEntryOptions</b> object to the MemoryCache.Set method while adding an item to the cache.</p>
<b>Example of CacheEntryOptions usage:</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using Microsoft.Extensions.Caching.Memory;
// Create an instance of CacheEntryOptions
var cacheEntryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30),
Priority = CacheItemPriority.High,
PostEvictionCallbacks =
{
new PostEvictionCallbackRegistration
{
EvictionCallback = (key, value, reason, state) =>
{
// Perform post-eviction cleanup or logging here
Console.WriteLine($"Cached item with key '{key}' was evicted due to '{reason}'.");
}
}
}
};
// Add an item to the cache with CacheEntryOptions
memoryCache.Set("myCacheKey", myCachedData, cacheEntryOptions);
</pre>
<p><b>CacheEntryOptions</b> in <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> offer a robust approach to control cached item behavior within <b>MemoryCache</b>. Leveraging these options allows fine-tuning caching behavior, setting expiration policies, handling evictions, and optimizing memory usage. Effective caching can significantly enhance the performance of your <a href="https://manish4dotnet.blogspot.com/p/net-core.html" target="_blank">.NET Core</a> applications, particularly when dealing with frequently accessed data.</p>
<p>Remember to choose a caching strategy carefully based on your application's requirements to ensure optimal performance and mitigate potential memory-related issues.</p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-55154772306592262802023-12-11T03:19:00.003+05:302024-02-04T06:23:51.192+05:30Prototype Design Pattern in C#<h2>What is Prototype Design Pattern?</h2>
<p>The prototype design pattern is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">creational design pattern</a> that allows creating new objects by cloning an existing object. This pattern is useful when the creation of an object is costly or complex, and we want to avoid repeating the same process for each new instance. By using the prototype pattern, we can create new objects by copying the properties and behaviors of an existing object, and then modifying them as needed.</p>
<p>One of the benefits of the prototype pattern is that it reduces the dependency on subclasses and factory methods. Instead of creating objects using specific constructors or factory methods, we can use a generic prototype object that can be cloned and customized. This makes the code more flexible and extensible, as we can add new types of objects without changing the existing code.</p>
<h2>Components of Prototype Pattern</h2>
<ul><li><b>Prototype:</b> This will be an interface or abstract class used for the types of objects that can be cloned. In our example, it is going to be the Employee Abstract Class.</li>
<li><b>ConcretePrototype:</b> This class will implement the Prototype abstract class or interface for cloning. In our example, it will be the PermanetEmployee and TemporaryEmployee Classes.</li>
<li><b>Client:</b> The client is the class that creates a new object by asking a prototype to clone itself.</li>
</ul>
<a name='more'></a>
<p>Let's dive into an example to illustrate the implementation of the Prototype pattern in C#.To implement the prototype pattern in C#</p>
<ol><li>We need to define an interface or an abstract class that declares a clone method. This method should return a copy of the object that implements the interface or inherits from the abstract class.</li>
<li>We need to create concrete classes that implement the interface or inherit from the abstract class, and override the clone method to return a copy of themselves.</li>
<li>We also need to create a prototype manager class that stores a collection of prototype objects and provides a method to access them by a key. This class acts as a registry for the prototype objects and allows retrieving them by their type or name.</li>
</ol>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>Here is an example of how to use the prototype pattern in C# to create different types of cars.</p>
<ol><li><b>Creating the Prototype:</b>We define an interface called <b>ICar</b> that declares a clone method and some properties:
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public interface ICar
{
string Model { get; set; }
string Color { get; set; }
int Price { get; set; }
public ICar Clone();
}
</pre>
</li>
<li><b>Creating the Concrete Prototypes:</b>Now we create two concrete classes that inherit from the <b>ICar</b> interface and implement the clone method to return a copy of themselves:
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class Sedan : ICar
{
public string Model { get; set; }
public string Color { get; set; }
public int Price { get; set; }
public ICar Clone()
{
return (ICar)this.MemberwiseClone();
}
}
</pre>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class Suv : ICar
{
public string Model { get; set; }
public string Color { get; set; }
public int Price { get; set; }
public ICar Clone()
{
return (ICar)this.MemberwiseClone();
}
}
</pre>
</li>
<li><b>Creating the Prototype Manager:</b>We create a prototype manager class that stores a dictionary of prototype objects and provides a method to access them by a key:
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class CarPrototypeManager
{
private Dictionary<string, ICar> _prototypes;
public CarPrototypeManager()
{
_prototypes = new Dictionary<string, ICar>();
}
public ICar GetPrototype(string key)
{
return _prototypes[key].Clone();
}
public void AddPrototype(string key, ICar prototype)
{
_prototypes.Add(key, prototype);
}
}
</pre>
</li>
<li><b>Client:</b>Finally, we can use the prototype manager class to create new car objects by cloning the existing prototypes and modifying their properties:
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
// Create a prototype manager and add some prototype objects
CarPrototypeManager manager = new CarPrototypeManager();
manager.AddPrototype("Sedan", new Sedan { Model = "Toyota Camry", Color = "White", Price = 30000 });
manager.AddPrototype("SUV", new Suv { Model = "Ford Explorer", Color = "Black", Price = 40000 });
// Create a new sedan object by cloning the prototype and changing the color
ICar sedan = manager.GetPrototype("Sedan");
sedan.Color = "Red";
// Create a new SUV object by cloning the prototype and changing the model and price
ICar suv = manager.GetPrototype("SUV");
suv.Model = "Honda CR-V";
suv.Price = 35000;
// Display the properties of the new objects
Console.WriteLine("Sedan: Model = {0}, Color = {1}, Price = {2}", sedan.Model, sedan.Color, sedan.Price);
Console.WriteLine("SUV: Model = {0}, Color = {1}, Price = {2}", suv.Model, suv.Color, suv.Price);
Console.ReadKey();
</pre>
</li>
</ol>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEEGML_zFSfe3EWnWnUOsH1c7h9AmTJ6qN46a7P6lgxLd-Vf-VKiW5M6s0lGUNYD0pfgH8hZQiKuyzw0Y9bJTKlIcaTVUSSAkvwtJzzqj6OJuK6XfRUhj5GVJ9dq6nbzz5DLNMJ9hTer3pV6BRZRj1RvfZwV1AADLN4IXQ43BcdvPFmJqlYL_Y7amsfao/s1600/Screenshot%202023-12-10%20144354.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="protoype design pattern" border="0" data-original-height="139" data-original-width="692" width="500" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEEGML_zFSfe3EWnWnUOsH1c7h9AmTJ6qN46a7P6lgxLd-Vf-VKiW5M6s0lGUNYD0pfgH8hZQiKuyzw0Y9bJTKlIcaTVUSSAkvwtJzzqj6OJuK6XfRUhj5GVJ9dq6nbzz5DLNMJ9hTer3pV6BRZRj1RvfZwV1AADLN4IXQ43BcdvPFmJqlYL_Y7amsfao/s1600/Screenshot%202023-12-10%20144354.png"/></a></div>
<p style="clear: both;">As you can see, we have created two new car objects by cloning the existing prototypes and changing their properties. This way, we have avoided creating new objects from scratch and reused the existing ones.</p>
<p>The prototype design pattern is a powerful and flexible way to create new objects by cloning an existing object. It can help us reduce the complexity and dependency of object creation, and make our code more dynamic and extensible.</p>
<p>However, we should also be careful about the cloning process, as it may involve deep or shallow copying, and may affect the references or values of the object's fields. We should also make sure that the prototype objects are immutable, or at least thread-safe, to avoid concurrency issues.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-61166221143509763602023-12-04T00:14:00.006+05:302024-02-04T06:24:02.826+05:30Builder Design Pattern in C#<h2>What is the Builder Design Pattern?</h2>
<p>The Builder Design Pattern is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">creational design pattern</a> that helps in constructing complex objects step by step. It separates the construction of an object from its representation, allowing the same construction process to create different representations. In C#, the Builder pattern is widely used to create objects with varying configurations while keeping the construction process unchanged.</p>
<p>The key idea is to separate the construction of a complex object from its representation, allowing the same construction process to create different representations.</p>
<p>So, the Builder Design Pattern is all about separating the construction process from its representation. When the construction process of your object is very complex, only you need to use the Builder Design Pattern.</p>
<h2>COmponents of Builder Design Pattern</h2>
<ul><li><strong>Abstract Builder:</strong> The Builder is an interface defining all the steps to make the concrete product.</li>
<li><strong>Concrete Builder</strong>: The Concrete Builder Classes implements the Abstract Builder interface and provides implementation to all the abstract methods. The Concrete Builder is responsible for constructing and assembling the individual parts of the product by implementing the Builder interface. It also defines and tracks the representation it creates.</li>
<li><strong>Director:</strong> The Director takes those individual processes from the Builder and defines the sequence to build the product.</li>
<li><strong>Product:</strong> The Product is a class, and we want to create this product object using the builder design pattern. This class defines different parts that will make the product.</li>
</ul>
<a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>Let's dive into an example to illustrate the implementation of the Builder pattern in C#:</p>
<p>Consider a scenario where we need to build a <b>Meal</b> object, consisting of different components like a burger, drink, fries, and a dessert. The Builder pattern can assist in constructing a <b>Meal</b> object by using a <b>MealBuilder</b>.</p>
<ol>
<li><strong>Creating the Product:</strong>Create a class file named <b>Meal.cs</b> and copy and paste the following code. This is our product class.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
/// <summary>
/// Represents the object that is being constructed
/// </summary>
public class Meal
{
public string Burger { get; set; }
public string Drink { get; set; }
public string Fries { get; set; }
public string Dessert { get; set; }
public void Display()
{
Console.WriteLine($"Burger: {Burger}, Drink: {Drink}, Fries: {Fries}, Dessert: {Dessert}");
}
}
</pre>
</li>
<li><strong>Creating the Abstract Builder:</strong>Create a interface file named <b>IMealBuilder.cs</b> and then copy and paste the following. This interface will provide the blueprint to create different types of products.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
/// <summary>
/// Abstract interface defining the steps for building the object
/// </summary>
public interface IMealBuilder
{
void AddBurger(string burger);
void AddDrink(string drink);
void AddFries(string fries);
void AddDessert(string dessert);
Meal GetMeal();
}
</pre>
</li>
<li><strong>Creating Concrete Builder Classes:</strong>The Concrete Builder classes follow the Builder interface and provide specific implementations of the building steps.Create a class file named <b>ConcreteMealBuilder.cs</b> and then copy and paste the following.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
/// <summary>
/// Implements the Builder interface to build the product
/// </summary>
public class ConcreteMealBuilder : IMealBuilder
{
private Meal _meal = new Meal();
public void AddBurger(string burger)
{
_meal.Burger = burger;
}
public void AddDrink(string drink)
{
_meal.Drink = drink;
}
public void AddFries(string fries)
{
_meal.Fries = fries;
}
public void AddDessert(string dessert)
{
_meal.Dessert = dessert;
}
public Meal GetMeal()
{
return _meal;
}
}
</pre>
</li>
<li><strong>Creating the Director:</strong>The Director Class in Builder Design Pattern is only responsible for executing the building steps in order. These steps are so generic that these steps will produce different products. It is helpful when producing products according to a specific order or configuration.Create a class file named <b>MealDirector.cs</b> and then copy and paste the following.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
/// <summary>
/// Manages the building process using the Builder
/// </summary>
public class MealDirector
{
public Meal Construct(IMealBuilder builder)
{
builder.AddBurger("Cheeseburger");
builder.AddDrink("Cola");
builder.AddFries("Large fries");
builder.AddDessert("Ice cream");
return builder.GetMeal();
}
}
</pre>
</li>
<li><strong>Client Code:</strong>The client code in the Builder Design Pattern will create a builder object, then pass that builder object to the director, and then the director will initiate the construction process. The end result is nothing but the product that is retrieved from the builder object.In our example, the Main method of the <b>Program</b> class is going to be the Client.
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using BuilderDesignPattern.Builder;
using BuilderDesignPattern.Director;
using BuilderDesignPattern.Product;
MealDirector director = new MealDirector();
IMealBuilder builder = new ConcreteMealBuilder();
Meal meal = director.Construct(builder);
meal.Display();
Console.ReadKey();
</pre>
</li>
</ol>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMHW-63uLuQ1AtVdnjUdb6MhiQsGZrrEdaMqYekCTcyF3itTlT3mxB4R6LIHGbLY2wvo8vGL4Yr3EqymSjJVfeBOGq9BePo9naq4Or3jSMvWuo-TEJHxCFCylXtd4ErIr4vHY8cxIY-6xRS-YxvhDu2BbmcXNTp425Xs0pvDmY4Y7QzElq2wAHigSnWcc/s1600/Screenshot%202023-12-03%20113946.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="builder design pattern output" border="0" data-original-height="115" data-original-width="916" width="700" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMHW-63uLuQ1AtVdnjUdb6MhiQsGZrrEdaMqYekCTcyF3itTlT3mxB4R6LIHGbLY2wvo8vGL4Yr3EqymSjJVfeBOGq9BePo9naq4Or3jSMvWuo-TEJHxCFCylXtd4ErIr4vHY8cxIY-6xRS-YxvhDu2BbmcXNTp425Xs0pvDmY4Y7QzElq2wAHigSnWcc/s1600/Screenshot%202023-12-03%20113946.png"/></a></div>
<p style="clear: both;">By using the Builder pattern, we can create different variations of meals by simply creating different concrete builders while keeping the construction process consistent.</p>
<p>Understanding and implementing the Builder pattern in C# enables flexible and scalable object construction while maintaining clear separation between the construction process and the resulting object.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-648572647376413322023-11-27T01:25:00.004+05:302024-02-04T06:25:07.090+05:30Angular17 - Deferred Loading Using Defer Block<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="Angular17 - Deferred Loading Using Defer Block" border="0" data-original-height="138" data-original-width="138" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png"/></a></div><p>Angular 17 recently came out with several exciting updates.it has an exciting new feature called <b>deferred loading</b></p>
<p><b>Lazy loading</b> is a method that helps web apps load things like scripts only when necessary. Instead of loading everything at the start, it waits to load less important stuff until the user does something like interacting with the page or scrolling to a certain point.</p>
<p>Lazy loading improves the user experience by making the initial page load faster. This means users can begin using the app sooner while the less important parts load quietly in the background. It also decreases the amount of internet data needed and eases the strain on the server.</p>
<p>In earlier versions of Angular, we were able to load a specific part of the application later using the <b>Router</b>, or by using dynamic <b>imports</b> along with <b>ngComponentOutlet</b>.</p>
<p>Angular17 now has a <b>@defer</b> control block enabling lazy-loading of the content of the block. Lazy-loading also applies to the dependencies of the content of the block: all the <b>components</b>, <b>directives</b> and <b>pipes</b> will be lazy-loaded, too.</p>
<p>I will demonstrate the key aspects of lazy loading in Angular 17, such as</p>
<ul>
<li>Using @defer with a logical expression</li>
<li>Using @defer with a declarative trigger condition</li>
</ul>
<a name='more'></a>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Using @defer with a logical expression</h2>
<p>In the below example, I make a checkbox and bind it to the <b>isChecked</b> property. Initial value of <b>isChecked</b> is false, so at the start, the checkbox is unccheked, and the content inside the <b>@defer </b>block doesn't appear.</p>
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h2>@defer with a logical expression</h2>
<div>
<input #checkboxDefer type="checkbox" [checked]="isChecked" (change)="onChange()" id="checkboxDefer" />
<label for="checkboxDefer">Check this checkbox to load the component</label>
</div>
<br>
@defer (when isChecked) {
<app-defer1 />
}
@placeholder {
<span>Placeholder</span>
}
@error {
<span>Error</span>
}
@loading(minimum 1s) {
<span>Loading...</span>
}
</pre>
<p>The <b>@defer (when logical_expression)</b> creates <b>@defer</b> block with the logical expression. I use the <b>isChecked</b> property as a logical expression, as it evaluates to a boolean value.</p>
<p>In the above example, we have four block types under the <b>@defer</b> block. These are-<p/>
<ul>
<li>An <b>@defer</b> block in Angular displays its content only when the <b>isChecked</b> turns true. Inside, there's a child component: <app-defer1 />.</li>
<li>A <b>@placeholder</b> block, it's rendered initially, before the <b>@defer</b> block is triggered</li>
<li>When the <b>@defer</b> block activates, Angular fetches its content from the server. While it loads, the <b>@loading</b> block is displayed.</li>
<li>If the loading fails, Angular shows the <b>@error</b> block</li>
</ul>
<p>The use of the <b>@placeholder</b>, <b>@loading</b> and <b>@error</b> blocks are optional, so we can use standalone <b>@defer</b> blocks, too.</p>
<p>Let's explore this code! When we launch the app, the <b>isChecked</b> is false. This means the <b>@defer</b> block doesn't triggered, and the content of the <b>@placeholder</b> block is visible.</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicZEjTl2k0kkK7Jq-iaeeZ7mU68jic1SY7joHv49t2GzwymvPyqmkUHm5ZrK-fqM6HDOFvKurhMVwtlaLt12auntK6WYNKmaRrv6Qk3figXHsrw0G5ERdCSPVxpjK8nXIZY1XrhFnZkKdZJT0_rjTvWiNm3vr-YmvC7upBsFRct5SI66RS0pp-vOabxDY/s1600/Screenshot%202023-11-26%20121901.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="place holder block content" border="0" data-original-height="211" data-original-width="1100" width="600" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicZEjTl2k0kkK7Jq-iaeeZ7mU68jic1SY7joHv49t2GzwymvPyqmkUHm5ZrK-fqM6HDOFvKurhMVwtlaLt12auntK6WYNKmaRrv6Qk3figXHsrw0G5ERdCSPVxpjK8nXIZY1XrhFnZkKdZJT0_rjTvWiNm3vr-YmvC7upBsFRct5SI66RS0pp-vOabxDY/s1600/Screenshot%202023-11-26%20121901.png"/></a></div>
<p style="clear: both;">When we check the checkbox, the <b>isChecked</b> turns true. Angular then loads the <b>@defer</b> block's content. It replaces the content of the <b>@placeholder</b> block and shows the <b>@loading</b> block. I set a minimum duration for this block to appear for at least one second. There's an option to set an "after" condition, which sets the minimum time to wait before the <b>@loading</b> block appears. If the content from the <b>@defer</b> block loads within this time, Angular won't display the <b>@loading</b> block.</p>
<p style="clear: both;">Content of the <b>@loading</b> block is visible for one second:</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8EeLRzjrZ9HLMzMk5EZiP4p-ywmlBcbFj776ezknZ-ayc6JHlXfvOmd04jg2ODSJ6mImEls1syFyfv7er3gfT5NM3CmReDGFBh1z4mEPxrj9W4B39DYRkk0tylD1O-XfqGT4XloVgdFyMZy22eQSc-1ju7zlvnxryh3XqDMTHnzRqXo3ZXGmh92FmWU4/s1600/Screenshot%202023-11-26%20122610.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="loading block content" border="0" data-original-height="211" data-original-width="658" width="600" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8EeLRzjrZ9HLMzMk5EZiP4p-ywmlBcbFj776ezknZ-ayc6JHlXfvOmd04jg2ODSJ6mImEls1syFyfv7er3gfT5NM3CmReDGFBh1z4mEPxrj9W4B39DYRkk0tylD1O-XfqGT4XloVgdFyMZy22eQSc-1ju7zlvnxryh3XqDMTHnzRqXo3ZXGmh92FmWU4/s1600/Screenshot%202023-11-26%20122610.png"/></a></div>
<p style="clear: both;">Then the content of the <b>@defer</b> block, the <app-defer1> component is shown:</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLw8Z98Q3mtVz7LXx9-R2uMGL9zetA-xz_dgDsIJGMzX6bacYReM0pCV1kk-RcSpUJsoQlpObB6b0xcFPHGugcqpuRxLR1ZeWjzAk4i3pcoFEpmjD7Ov7ZNUdGtHARkD7H5p4Ja3txV5-lMgidvX1GLAShSZUMha8hamO50M_7cs1CrSuCd0W8vDqRb6s/s1600/Screenshot%202023-11-26%20122803.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="defer block content" border="0" data-original-height="219" data-original-width="735" width="600" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLw8Z98Q3mtVz7LXx9-R2uMGL9zetA-xz_dgDsIJGMzX6bacYReM0pCV1kk-RcSpUJsoQlpObB6b0xcFPHGugcqpuRxLR1ZeWjzAk4i3pcoFEpmjD7Ov7ZNUdGtHARkD7H5p4Ja3txV5-lMgidvX1GLAShSZUMha8hamO50M_7cs1CrSuCd0W8vDqRb6s/s1600/Screenshot%202023-11-26%20122803.png"/></a></div>
<p style="clear: both;">In the Developer tools, it's visible that after checking the box, Angular loaded a chunk of the application, which includes the content from the <b>@defer</b> block.</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCMk-XGzgrKCFQHXAXnklgsBIvSMVwDMFOH9sUabbpWaElNUJW88UwXmkryaOsNC1pXpSmPCRxaHOta3ay8bi9DKjg0j-t53HbIkzHFCSRRhKO86QQ5HyGsESI-BHCeBEdcmsPX9MFyHSA0aaMj2zAOJS0XNdGthT7h8jaii9bCVWSt_QwWxoSn6J7fog/s1600/Screenshot%202023-11-26%20123213.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="loading chunk" border="0" data-original-height="710" data-original-width="1211" width="600" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCMk-XGzgrKCFQHXAXnklgsBIvSMVwDMFOH9sUabbpWaElNUJW88UwXmkryaOsNC1pXpSmPCRxaHOta3ay8bi9DKjg0j-t53HbIkzHFCSRRhKO86QQ5HyGsESI-BHCeBEdcmsPX9MFyHSA0aaMj2zAOJS0XNdGthT7h8jaii9bCVWSt_QwWxoSn6J7fog/s1600/Screenshot%202023-11-26%20123213.png"/></a></div>
<h2 style="clear: both;">Using @defer with a declarative trigger condition</h2>
<p>Deferred blocks can be triggered using various declarative types:</p>
<ul><li>on interaction</li><li>on hover</li><li>on idle</li><li>on timer</li><li>on viewport</li></ul>
<p>Below are the examples of all these:</p>
<ul>
<li><b>@defer on interaction:</b>Angular renders the on interaction block, when the user interacts with its <b>@placeholder</b> block. An interaction can be a click, touch focus, or input events:
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@defer on interaction</h3>
@defer (on interaction) {
<span>Clicked</span>
}
@placeholder {
<span>Placeholder (click on it!)</span>
}
</pre>
</li>
<li><b>@defer on idle:</b>Angular renders the on idle block, when the browser reaches an idle state after the page has been loaded:
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@defer on idle</h3>
@defer (on idle) {
<span>Browser has reached an idle state</span>
}
@placeholder {
<span>Placeholder</span>
}
</pre>
</li>
<li><b>@defer on hover:</b>Angular renders the on hover block, when the user hovers over its @placeholder block:
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@defer on hover</h3>
@defer (on hover) {
<span>Hovered</span>
}
@placeholder {
<span>Placeholder (hover it!)</span>
}
</pre>
</li>
<li><b>@defer on timer:</b>The on timer block is rendered after the specified time is elapsed:
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@defer on timer(5s)</h3>
@defer (on timer(5s)) {
<span>Visible after 5s</span>
}
@placeholder {
<span>Placeholder</span>
}
</pre>
</li>
<li><b>@defer on viewport:</b>Angular renders the on viewport block, when the placeholder enters the browser's viewport:
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@defer on viewport</h3>
@defer (on viewport) {
<app-defer2 text="The block entered the viewport" />
}
@placeholder {
<span>Placeholder</span>
}
</pre>
</li>
<li><b>Prefetch:</b>Next to a trigger condition, we can specify an additional prefetch condition.In prefetch, Angular loads the content of the <b>@defer</b> block, but it's not rendered, the <b>@placeholder</b> remains visible.Then we hover on the placeholder, and Angular renders the prefetched block.
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>Prefetch</h3>
@defer (on interaction; prefetch on hover) {
<app-defer3 />
}
@placeholder {
<span>Placeholder (hover it, then click on it!)</span>
}
</pre>
</li>
</ul>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/ng17-deferred-loading" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-91229864082884886032023-11-19T22:44:00.002+05:302023-11-20T02:08:45.556+05:30Angular 17 : New control flow syntax<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png" style="clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;"><img alt="Angular17- New control flow" border="0" data-original-height="138" data-original-width="138" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png"/></a></div>
<p>Angular 17 recently came out with several exciting updates. One notable addition is the <b>Control Flow</b> feature. This new feature simplifies template writing by introducing a direct way to handle control flow within the template itself. Now, there's no need to rely on directives like *ngIf, *ngFor, and *ngSwitch for control flow as this new syntax streamlines the process.</p>
<p>This post will demonstrate a basic project using a new control flow method, moving away from the traditional directive-based approach. You can go through my other <b>Angular</b> post <a href="https://manish4dotnet.blogspot.com/p/angular.html" target="_blank">here</a>.Let's begin right away!</p>
<h2>Angular Project Setup</h2>
<p>Before we start using the new feature, let's make sure you have an Angular project set up and ready to go. If you haven't done so yet, create a new Angular project using these commands with the Angular CLI:</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
npm install -g @angular/cli@latest
ng new ng17-control-flows
</pre>
<p>This command creates a fresh Angular project, including all the essential files and dependencies with the latest version.</p>
<p>Once it's set up, open the <b>app.component.html</b> file and remove the default Angular code. Let's add a basic HTML structure to it instead.</p>
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h1>NG -17 :New Control Flows</h1>
</pre>
<h2>Conditionally rendered control blocks: @if and @else</h2>
<p>Let’s start with the replacement of *ngIf.</p>
<p>In the first example, I create a checkbox and bind it to the <b>isChecked</b> property.Starting with a default value of true, the checkbox appears checked, displaying the content within the @if block.The examples below are from the <b>app.component.html</b> <a href="https://manish4dotnet.blogspot.com/2023/04/angular-html-template-in-angular.html" target="_blank">template</a> file:</p>
<a name='more'></a>
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@if and @else</h3>
<div>
<input #checkbox type="checkbox" [checked]="isChecked" (change)="toggle()" id="checkbox" />
</div>
<div>
@if (isChecked) {
<span>Checked</span>
}
@else {
<span>Not checked</span>
}
</div>
</pre>
<p>I use <b>isChecked</b> as a logical expression that gives a boolean value. Adding an <b>@else</b> block below <b>@if</b> renders when the expression in <b>@if</b> is false, meaning if the <b>isChecked</b> turns false. If I uncheck the checkbox, Angular shows the @else block content.</p>
<h2>Switch control flow with with @switch, @case and @default</h2>
<p>In the following example, I set up four radio buttons along with a property called <b>radioValue</b>. Initially, the property holds the value 1. When a user clicks on any of the radio buttons, the radioValue changes to either 1, 2, 3, or 4 depending on the selection.</p>
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@switch and @case</h3>
<div>
<div>
<input type="radio" [checked]="radioValue === 1" (change)="radioValueChange(1)" id="radio1" />
<label for="radio1">1</label>
</div>
<div>
<input type="radio" [checked]="radioValue === 2" (change)="radioValueChange(2)" id="radio2" />
<label for="radio2">2</label>
</div>
<div>
<input type="radio" [checked]="radioValue === 3" (change)="radioValueChange(3)" id="radio3" />
<label for="radio3">3</label>
</div>
<div>
<input type="radio" [checked]="radioValue === 4" (change)="radioValueChange(4)" id="radio4" />
<label for="radio4">4</label>
</div>
</div>
<div>
@switch (radioValue) {
@case (1) {
<span>Case 1</span>
}
@case (2) {
<span>Case 2</span>
}
@default {
<span>Default case (Not 1 or 2)</span>
}
}
</div>
</pre>
<p>I nested three blocks into the @switch block:</p>
<ul><li>the contents of the @case (1) { block is rendered, when the radioValue equals to 1</li>
<li>the contents of the @case (2) { block is rendered, when the radioValue equals to 2</li>
<li>the contents of the @default { block is rendered, when the radioValue doesn't equal to the values we specified in the @case blocks</li></ul>
<h2>Using @for blocks to render items of a collection</h2>
<p>Let's define the items array in the <a href="https://manish4dotnet.blogspot.com/2023/04/angular-component.html" target="_blank">component's</a> class:</p>
<pre class="brush:javascript;class-name: 'divSyntax'" style="text-align: left;">
collection = [
{ id: 1, name: 'ABC' },
{ id: 2, name: 'XYZ' },
];
</pre>
<p>We can use an @for (item of items; track item.id) { block to render a collection's elements:</p>
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@for</h3>
<ul>
@for (item of collection; track item.id;) {
<li><strong>{{item.name}}</strong></li>
}
</ul>
</pre>
<p>For each item in the collection, it's essential to have a distinct property (such as an ID) that we reference using the track argument. If the collection comprises strings or numbers instead of objects, we can directly use the item as the track value in the loop: <b>@for (item of items; track item)</b>.</p>
<h2>Using an @empty block to handle the empty collections passed to @for</h2>
<p>We can include an <b>@empty</b> block below the <b>@for</b> block. The <b>@empty</b> block displays its content when the collection provided to the <b>@for</b> block is empty.</p>
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
<h3>@empty</h3>
<ul>
@for (item of emptyCollection; track item;) {
<li><strong>{{item}}</strong></li>
}
@empty {
<span>The collection is empty</span>
}
</pre>
<h2>Output</h2>
<div class="separator" style="clear: both; text-align: left;"><iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='400' height='322' src='https://www.blogger.com/video.g?token=AD6v5dxEtNhRfx7xfPWK05IDCPj01fW0uiIa-c3uzCsD8fXB0a7zf5nacGGcmYKKC1ay-HwWkinP7BUyf-4dZ1-hbg' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<h2 style="clear: both;margin-top:10px">Migrate ngIf, ngFor, and ngSwitch to the new control block syntax</h2>
<p>To convert the old structural directives in an app's templates to the new control blocks, run the following schematic:</p>
<pre class="brush:html;class-name: 'divSyntax'" style="text-align: left;">
ng g @angular/core:control-flow-migration
</pre>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/ng17-control-flows" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-43084905922029080352023-11-05T08:41:00.007+05:302024-02-04T06:25:27.224+05:30Abstract Factory Design Pattern in C#<p>In this article, I will explain the Abstract Factory Design Pattern in C# with practical examples. I encourage you to check out our previous article, which covers the <a href="https://manish4dotnet.blogspot.com/2023/10/design-pattern-factory-design-pattern.html" target="_blank">Factory Design Pattern</a> in C# along with an example.The Abstract Factory Design Pattern falls under the category of creational design patterns and is widely applied in real-world software development. In this article, we'll explore the following topics</p>
<h2>What is the Abstract Factory Design Pattern?</h2>
<p>The <b>Abstract Factory Design Pattern</b> is a <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">creational design pattern</a> that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is a higher-level pattern than the <a href="https://manish4dotnet.blogspot.com/2023/10/design-pattern-factory-method-design.html" target="_blank">Factory Method pattern</a>, which deals with creating individual objects, while the Abstract Factory creates families of objects.</p>
<p>"Abstract" means hiding details, "Factory" refers to the entity that creates things, and "Pattern" indicates a design approach. Therefore, the Abstract Factory Pattern is a method in software design that allows you to wrap a set of factories with a shared theme.</p>
<p>Put simply, the Abstract Factory serves as a high-level factory that generates other factories. It's often referred to as the "Factory of Factories." This <a href="https://manish4dotnet.blogspot.com/2023/08/design-patterns-building-robust-and.html" target="_blank">design pattern</a>, the Abstract Factory, offers a way to create groups of related products without specifying the actual objects to be created.</p>
<a name='more'></a>
<h2>Components of the Abstract Factory Pattern</h2>
<div>
<ol style="text-align: left;">
<li><b>Abstract Factory:</b>This is an interface or an abstract class that declares a set of methods for creating a family of related objects. Each method typically corresponds to a different product or object type.</li>
<li><b>Concrete Factories:</b>These are concrete implementations of the abstract factory interface. Each concrete factory is responsible for creating a specific family of related objects.</li>
<li><b>Abstract Products:</b>These are interfaces or abstract classes that declare the methods that concrete product classes must implement.</li>
<li><b>Concrete Products:</b>These are the actual classes that implement the abstract product interfaces. There can be multiple concrete product classes for each abstract product.</li>
<li><b>Client:</b>Uses interfaces declared by AbstractFactory and AbstractProduct classes. This class will use our Abstract Factory and Abstract Product interfaces to create a family of products.</li>
</ol>
</div>
<div id="adContent" style="padding-bottom:15px;padding-top:15px">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-1057718374354714"
data-ad-slot="4432765064"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h2>Understand Abstract Factory Design Pattern Through Example</h2>
<b>Step 1: Creating Abstract Products</b>
<p>Here, we need to declare interfaces for creating abstract products. As we will create two types of familiar products, such as Button and Textboax, here we need to create two interfaces or abstract classes representing each abstract product type. Here, I am going to create two interfaces.</p>
<b>IButton.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AbstractFactoryPatternExample.Product.Button
{
public interface IButton
{
void Render();
}
}
</pre>
<b>ITextBox.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AbstractFactoryPatternExample.Product.TextBox
{
public interface ITextBox
{
void Render();
}
}
</pre>
<b>Step 2: Creating Concrete Products</b>
<p>Here, we must define the concrete product object the corresponding concrete factory will create. How the concrete factory will create the product object will be discussed later in the article when we discuss the concrete factory component. Remember that the concrete product classes must implement the Abstract Product Interface. In our example, the concrete product class must implement the <b>IButton</b> or <b>ITextBox</b> interface. So, as per our requirements, let us create four concrete products, i.e., WindowButton, MacButton, WindowTextBox, and MacTextBox.</p>
<b>WindowButton.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AbstractFactoryPatternExample.Product.Button
{
public class WindowButton : IButton
{
public void Render()
{
Console.WriteLine("Render window button");
}
}
}
</pre>
<b>MacButton.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AbstractFactoryPatternExample.Product.Button
{
public class MacButton : IButton
{
public void Render()
{
Console.WriteLine("Render mac button");
}
}
}
</pre>
<b>WindowTextBox.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AbstractFactoryPatternExample.Product.TextBox
{
public class WindowTextBox:ITextBox
{
public void Render()
{
Console.WriteLine("Render window textbox");
}
}
}
</pre>
<b>MacTextBox.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
namespace AbstractFactoryPatternExample.Product.TextBox
{
public class MacTextBox:ITextBox
{
public void Render()
{
Console.WriteLine("Render mac textbox");
}
}
}
</pre>
<b>Step 3: Creating Abstract Factory</b>
<p>Here, we need to create an interface for operations that will create AbstractProduct objects. In our example, it is going to be <b>IUIFactory</b>.So, create a interface file with the name <b>IUIFactory.cs</b></p>
<b>IUIFactory.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using AbstractFactoryPatternExample.Product.Button;
using AbstractFactoryPatternExample.Product.TextBox;
namespace AbstractFactoryPatternExample.Factory
{
public interface IUIFactory
{
IButton CreateButton();
ITextBox CreateTextBox();
}
}
</pre>
<p>As you can see, this interface contains two methods. The <b>CreateButton</b> method will create different variants of buttons, whereas the <b>CreateTextBox</b> method will create different variants of textbox.Remember, here we're just stating the methods and specifying that both methods return abstract products - namely, <b>IButton</b> and <b>ITextbox</b>.</p>
<b>Step 4: Creating Concrete Factories</b>
<p>Here, we must create concrete classes that implement the operations to create concrete product objects. These classes will implement the AbstractFactory interface and provide implementations for the two interface methods. In our example, we will create two Concrete Classes, i.e., <b>WindowUIFactory</b> and MacUIFactory<b></b>.</p>
<b>WindowUIFactory.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using AbstractFactoryPatternExample.Product.Button;
using AbstractFactoryPatternExample.Product.TextBox;
namespace AbstractFactoryPatternExample.Factory
{
public class WindowUIFactory : IUIFactory
{
public IButton CreateButton()
{
return new WindowButton();
}
public ITextBox CreateTextBox()
{
return new WindowTextBox();
}
}
}
</pre>
<b>MacUIFactory.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using AbstractFactoryPatternExample.Product.Button;
using AbstractFactoryPatternExample.Product.TextBox;
namespace AbstractFactoryPatternExample.Factory
{
public class MacUIFactory : IUIFactory
{
public IButton CreateButton()
{
return new MacButton();
}
public ITextBox CreateTextBox()
{
return new MacTextBox();
}
}
}
</pre>
<b>Step 5: Client</b>
<p>The Client class uses AbstractFactory and AbstractProduct interfaces to create a family of related objects. The following example code is self-explained, so please go through the comment lines for a better understanding.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using AbstractFactoryPatternExample.Factory;
using AbstractFactoryPatternExample.Product.Button;
using AbstractFactoryPatternExample.Product.TextBox;
// Create Windows UI
IUIFactory factory = new WindowUIFactory();
IButton button = factory.CreateButton();
ITextBox textBox = factory.CreateTextBox();
button.Render(); // This will render the appropriate button for the chosen factory.
textBox.Render(); // This will render the appropriate text box.
Console.WriteLine("-----------------------------------------------");
// Create Mac UI
IUIFactory factory1 = new MacUIFactory();
IButton button1 = factory1.CreateButton();
ITextBox textBox1 = factory1.CreateTextBox();
button1.Render(); // This will render the appropriate button for the chosen factory.
textBox1.Render(); // This will render the appropriate text box.
Console.ReadLine();
</pre>
<b>Output</b>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEho4bhdApwqQPY7DP2VRZQHADY1MiocqK_Enpr68yrfE91-XCwBJP3p7RANu3hoSlPOqVD0mZGLwzDIE0C6Z-_euXaytj32HIWsjOD1gJVQ5xZwWO5h9FPdk38X53-PQa7BKXm1f24FwMZokKOaY5qwFj5M7V2EoWY77fon_1762ZhWsT6p8360K1w2If0/s1600/Screenshot%202023-11-04%20210456.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="" border="0" data-original-height="217" data-original-width="656" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEho4bhdApwqQPY7DP2VRZQHADY1MiocqK_Enpr68yrfE91-XCwBJP3p7RANu3hoSlPOqVD0mZGLwzDIE0C6Z-_euXaytj32HIWsjOD1gJVQ5xZwWO5h9FPdk38X53-PQa7BKXm1f24FwMZokKOaY5qwFj5M7V2EoWY77fon_1762ZhWsT6p8360K1w2If0/s1600/Screenshot%202023-11-04%20210456.png"/></a></div>
<p style="clear: both;">The Abstract Factory Design Pattern enables easy switching between different families of objects, like Windows and macOS UI, by merely changing the concrete factory. This flexibility and maintainability are advantageous, especially in complex systems with multiple platforms or variations.</p>
<p>In essence, this <a href="https://manish4dotnet.blogspot.com/2023/08/design-patterns-building-robust-and.html" target="_blank">pattern</a> facilitates the creation of related objects with a unified interface. It minimizes code dependency, making it easier to maintain, test, and expand your codebase. For systems with diverse platforms or variations, the Abstract Factory Pattern proves to be a valuable addition.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-71142716870391297752023-10-22T07:49:00.006+05:302023-12-18T01:06:16.201+05:30Factory Method Design Pattern in C#<p>The Factory Method Design Pattern belongs to the <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">Creational Design Pattern</a> Category.As part of this article, we will discuss this design pattern in detail with example</p>
<h2>What is Factory Method Design Pattern</h2>
<p>As per Gang of Four, the Factory Method Design Pattern states that <b>Defines an interface for creating an object but lets the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.</b></p>
<p>In simple words, The Factory Method Design Pattern is used when we create the object without exposing the object creation logic to the client. In the factory method design pattern, we will create an abstract class as the Factory class, which will create and return the product instance, but it will let the subclasses decide which class to instantiate.</p>
<h2>The Key Components:</h2>
<div>
<ol style="text-align: left;">
<li><b>Factory Interface/Abstract Class:</b>This serves as a blueprint for an interface or an abstract class that contains a method for creating objects. Typically, this method is named something like 'createProduct()' or 'factoryMethod()'.</li>
<li><b>Concrete Factories:</b>These are tangible classes that implement the factory interface. They provide specific implementations of the 'createProduct()' method. Each concrete factory is responsible for producing a particular type of product.</li>
<li><b>Product Interface/Abstract Class:</b>This defines an interface or an abstract class for the products generated by the factories. Product classes usually share common attributes or methods.</li>
<li><b>Concrete Products:</b>These are the real-deal classes that implement the product interface. Each concrete product embodies a specific type of object.</li>
</ol>
</div>
<a name='more'></a>
<h2>EXAMPLE TO UNDERSTAND FACTORY Method DESIGN PATTERN IN C#</h2>
<p>Let's dive into the Factory Method Design Pattern using a scenario of different beverages in a cafe, which we use in our previous article <a href="https://manish4dotnet.blogspot.com/2023/10/design-pattern-factory-design-pattern.html" target="_blank">Factory Design Pattern</a>.</p>
<h2>Step-1 : Create the Abstract Product or Product Interface (Beverage)</h2>
<p>We need to create either an interface or an abstract class that will expose the operations a beverage should have. So, create a interface file named <b>IBeverage.cs</b> and copy and paste the following code.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public interface IBeverage
{
public string Serve();
}
</pre>
<p>Now We will create two Product classes to implement the above interface.</p>
<h2>Step-2 : Creating Product Classes(Coffee and Tea)</h2>
<p>In our example we will take two beverage products- Coffee and Tea. So we will create two classes by implementing the <b>IBeverage.cs</b> interface. Thse two classes will be:- <b>Coffee.cs</b> and <b>Tea.cs</b></p>
<b>Coffee.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class Coffee : IBeverage
{
public string Serve()
{
return "Serving Coffee";
}
}
</pre>
<b>Tea.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class Tea:IBeverage
{
public string Serve()
{
return "Serving Tea";
}
}
</pre>
<p>So, we have created two Product classes <b>Coffee.cs</b> and <b>Tea.cs</b> that implements the <b>IBeverage.cs</b> interface. Now we will create the Factory class.</p>
<h2>Step-3 : Creating Factory Interface(IBeverageFactory)</h2>
<p>Create a interface file named <b>IBeverageFactory.cs</b>.This interface will contain a method for creating object named <b>createBeverage()</b></p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FactoryMethodDesignPatternDemo.Product;
namespace FactoryMethodDesignPatternDemo.Factory
{
public interface IBeverageFactory
{
public IBeverage createBeverage();
}
}
</pre>
<h2>Step-4 : Create concrete factorie classes(CoffeeFactory and TeaFactory)</h2>
<p>The concrete factory class implements the Factory interface class and overrides the factory method. The override Factory Method will return an instance of a Concrete Product via the base Product interface.As we have two types of beverage, we will create two concrete factory classes- <b>CoffeeFactory.cs</b> and <b>TeaFactory.cs</b></p>
<b>CoffeeFactory.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FactoryMethodDesignPatternDemo.Product;
namespace FactoryMethodDesignPatternDemo.Factory
{
public class CoffeeFactory : IBeverageFactory
{
public IBeverage createBeverage()
{
return new Coffee();
}
}
}
</pre>
<b>TeaFactory.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FactoryMethodDesignPatternDemo.Product;
namespace FactoryMethodDesignPatternDemo.Factory
{
public class TeaFactory : IBeverageFactory
{
public IBeverage createBeverage()
{
return new Tea();
}
}
}
</pre>
<h2>Step-5 : Consuming the Factory Method in the Client Code</h2>
<p>The client code works with an instance of a concrete factory, i.e., we need to create an instance of either CoffeeFactory,or TeaFactory. Then, we need to call the <b>createBeverage</b> method on the concrete factory instance, which will return the actual product instance via the product interface, i.e., Beverage type.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FactoryMethodDesignPatternDemo.Factory;
using FactoryMethodDesignPatternDemo.Product;
//CoffeeFactory createBeverage method will return an instance of Coffee Product
IBeverage coffee =new CoffeeFactory().createBeverage();
if (coffee != null)
{
Console.WriteLine(coffee.Serve());
}
Console.WriteLine("--------------------------------");
//TeaFactory createBeverage method will return an instance of Tea Product
IBeverage tea = new TeaFactory().createBeverage();
if (tea != null)
{
Console.WriteLine(tea.Serve());
}
Console.ReadLine();
</pre>
<p>When we run the application, it displays the output as expected, as shown in the below image.</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhiUMf9VqXmIQqKDvdHn8Sfy4akF_csXxjq_WC5sVoVo-g_LCoRpuGXEr_LYiE1sEfhPSGGy-5wCovbM-9J8U_g8x2qm4bMp1-kh5yrxWe0EApNxORv7pNiBj4Ykp5qwB1ba1KeZjgSRpJxU-I5nZDLOfE4OlTrOUMTvnODFP2iG-C4rBQ3q5RDuY3mouM/s1600/Screenshot%202023-10-21%20195430.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="factory method design pattern" border="0" data-original-height="166" data-original-width="452" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhiUMf9VqXmIQqKDvdHn8Sfy4akF_csXxjq_WC5sVoVo-g_LCoRpuGXEr_LYiE1sEfhPSGGy-5wCovbM-9J8U_g8x2qm4bMp1-kh5yrxWe0EApNxORv7pNiBj4Ykp5qwB1ba1KeZjgSRpJxU-I5nZDLOfE4OlTrOUMTvnODFP2iG-C4rBQ3q5RDuY3mouM/s1600/Screenshot%202023-10-21%20195430.png"/></a></div>
<h2 style="clear: both;">UML(Class) Diagram</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeLNmmsPtT4bmClW_dYuGD7pYgt9Xe_Awuiplj9h50llaP0UcN4dRMdZc28S7-zD8XEwHr35DM8e2ji4YGRO5xs9VdwsmtrrBY7HgED7P9L-aYTcyu2is1sRPDrcbH9LUy4w6yBsT_oQC2O6IefYT9yZAddaw9m6aALlUlvQRDunygy_YP1JNId_4DHmI/s1600/FactoryMethodDesignPattern.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="factory method design pattern uml" border="0" data-original-height="377" data-original-width="771" width="690" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeLNmmsPtT4bmClW_dYuGD7pYgt9Xe_Awuiplj9h50llaP0UcN4dRMdZc28S7-zD8XEwHr35DM8e2ji4YGRO5xs9VdwsmtrrBY7HgED7P9L-aYTcyu2is1sRPDrcbH9LUy4w6yBsT_oQC2O6IefYT9yZAddaw9m6aALlUlvQRDunygy_YP1JNId_4DHmI/s1600/FactoryMethodDesignPattern.png"/></a></div>
<p>The Factory Method Design Pattern is particularly useful in scenarios where you want to decouple the client code from the specific classes it needs to instantiate, making your code more maintainable and easier to extend.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-45782825682663144452023-10-01T08:34:00.007+05:302023-12-18T01:06:30.373+05:30Factory Design Pattern in C#<p>The Factory Design Pattern is one of the most frequently used design patterns in real-time applications. The Factory Design Pattern in C# falls under the Creational <a href="https://manish4dotnet.blogspot.com/p/design-pattern.html" target="_blank">Design Patterns</a> Category.</p>
<h2>What is Factory Design Pattern in C#?</h2>
<p>Let us first try to understand the definitions of the factory design pattern.</p>
<p>According to Gang of Four (GoF), the Factory Design Pattern states that <b>A factory is an object used for creating other objects.</b> In technical terms, we can say that a factory is a class with a method. That method will create and return different objects based on the received input parameter.</p>
<p>In simple words, when we have a main class(super class) and several different types of classes(subclasses) that are related to it, and we want to make an object from one of these related classes based on some information, we use something called the Factory Design Pattern in C#.</p>
<h2>The Key Components:</h2>
<div>
<ol style="text-align: left;">
<li><b>Product Interface/Abstract Class:</b>This defines an interface or an abstract class for the products generated by the factories. Product classes usually share common attributes or methods.</li>
<li><b>Concrete Products:</b>These are the real-deal classes that implement the product interface. Each concrete product embodies a specific type of object.</li>
<li><b>Factory Class:</b>This class contains a method for creating objects.Typically, this method is named something like 'createProduct()' or 'factoryMethod()'.</li>
</ol>
</div>
<a name='more'></a>
<h2>Example to Understand Factory Design Pattern in C#</h2>
<p>Let's dive into the Factory Design Pattern using a scenario of different beverages in a cafe.</p>
<h2>Step-1 : Create the Abstract Product or Product Interface (Beverage)</h2>
<p>We need to create either an interface or an abstract class that will expose the operations a beverage should have. So, create a interface file named <b>IBeverage.cs</b> and copy and paste the following code.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public interface IBeverage
{
public string Serve();
}
</pre>
<p>Now We will create two Product classes to implement the above interface.</p>
<h2>Step-2 : Creating Product Classes(Coffee and Tea)</h2>
<p>In our example we will take two beverage products- Coffee and Tea. So we will create two classes by implementing the <b>IBeverage.cs</b> interface. Thse two classes will be:- <b>Coffee.cs</b> and <b>Tea.cs</b></p>
<b>Coffee.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class Coffee : IBeverage
{
public string Serve()
{
return "Serving Coffee";
}
}
</pre>
<b>Tea.cs</b>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class Tea:IBeverage
{
public string Serve()
{
return "Serving Tea";
}
}
</pre>
<p>So, we have created two Product classes <b>Coffee.cs</b> and <b>Tea.cs</b> that implements the <b>IBeverage.cs</b> interface. Now we will create the Factory class.</p>
<h2>Step-3 : Creating Factory Class(BeverageFactory)</h2>
<p>Create a class file named <b>BeverageFactory.cs</b>.This class will contain the logic to create and initialize the appropriate object and returns that object based on some condition. As you can see, this class contains one static method. That static method takes one string parameter, and based on the parameter value, it will create and return the appropriate product instance (Coffee, or Tea) to the client.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public class BeverageFactory
{
public static IBeverage GetBeverage(string beverageName)
{
IBeverage beverage = null;
if (beverageName == "Coffee")
{
beverage = new Coffee();
}
else if (beverageName == "Tea")
{
beverage = new Tea();
}
return beverage;
}
}
</pre>
<h2>Step-4 : Using factory class in client to get the product instance</h2>
<p>Now we need to use the Factory class in our client class(in our example it in Program.cs) as follows</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using FactoryDesignPatternDemo.Factory;
using FactoryDesignPatternDemo.Product;
IBeverage beverage = BeverageFactory.GetBeverage("Coffee");
if (beverage != null)
{
Console.WriteLine(beverage.Serve());
Console.WriteLine("Press any key...");
Console.ReadLine();
}
</pre>
<p>As you can see, we are calling the Static <b>GetBeverage</b> method of the <b>BeverageFactory</b> class by passing the Beverage Type which instance we need to create. Once the <b>GetBeverage</b> method returns the appropriate product instance, we consume the methods as it is</p>
<h2>Output</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh81H1aLBrLmdS6UHAordHZQLW7yyFFIJ9q0Z-pjpGrlfyJ7nZfZxLtzUTycsN29zM_md12doaGKc55mwU2hU_58NnsZu8tUAr_Bh16hXnJJyMYGrtmJ9Lvhgdjc1oahAOVjsw0Laj4-jQTZMcHmK7RsbrZUEo6VeGYt0VoTBuRt5zrH6uXirkb2XpPbZI/s1600/Screenshot%202023-09-30%20204945.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="factory design pattern" border="0" data-original-height="131" data-original-width="258" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh81H1aLBrLmdS6UHAordHZQLW7yyFFIJ9q0Z-pjpGrlfyJ7nZfZxLtzUTycsN29zM_md12doaGKc55mwU2hU_58NnsZu8tUAr_Bh16hXnJJyMYGrtmJ9Lvhgdjc1oahAOVjsw0Laj4-jQTZMcHmK7RsbrZUEo6VeGYt0VoTBuRt5zrH6uXirkb2XpPbZI/s1600/Screenshot%202023-09-30%20204945.png"/></a></div>
<h2 style="clear: both;">UML(Class) Diagram</h2>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhycP0XsQ2UOXMjVcjPpYO0sFKZrlKTAEDAPgccVGfmD1hzqSbnSMONY846nF_WP5GbeZTxrcwpTEiLBz1mbLIALGOiQ_qcEkSV0OPGuWAjDM9bYhKTiLAVToEkfwIxPinFrXiF6I21VZ_CpjpkelZcou97JHdRmjhb8rDaTAABoRL-3kuiiScfE0Ut4pY/s1600/FactoryDesignPattern.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="Factory Design Pattern UML" border="0" data-original-height="391" data-original-width="521" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhycP0XsQ2UOXMjVcjPpYO0sFKZrlKTAEDAPgccVGfmD1hzqSbnSMONY846nF_WP5GbeZTxrcwpTEiLBz1mbLIALGOiQ_qcEkSV0OPGuWAjDM9bYhKTiLAVToEkfwIxPinFrXiF6I21VZ_CpjpkelZcou97JHdRmjhb8rDaTAABoRL-3kuiiScfE0Ut4pY/s1600/FactoryDesignPattern.png"/></a></div>
<h2 style="clear: both;">Problems of Simple Factory Pattern</h2>
<ol>
<li>If we need to add any new product (i.e., a new beverage), then we need to add a new if else condition in the <b>GetBeverage</b> method of the <b>BeverageFactory</b> class. This violates the open/closed design principle.</li>
<li>We also have a tight coupling between the Factory <b>(BeverageFactory)</b> and Product classes <b>(Coffee and Tea)</b>. We can overcome these problems using the <a href="https://manish4dotnet.blogspot.com/2023/10/design-pattern-factory-method-design.html" target="_blank">Factory Method Design Pattern</a>, which we will discuss in our upcoming articles.</li>
</ol>
<h2>Advantages of Factory Design Pattern in C#:</h2>
<ul><li><strong>Decoupling:</strong> The Factory Design Pattern promotes decoupling. The client code is decoupled from the specific classes it needs to instantiate, which helps achieve the principle of “separation of concerns.”</li>
<li><strong>Flexibility:</strong> It offers flexibility in terms of which class to instantiate. If we need to change the instantiation logic or introduce new classes, we only need to change the factory, leaving the client code untouched.</li>
<li><strong>Consistent Object Creation:</strong> Having a central place for object creation ensures that all objects are created consistently, following the same rules or configurations.</li>
<li><strong>Single Responsibility Principle:</strong> By delegating the responsibility of object creation to factories, the main business logic classes can focus on their primary responsibilities.</li>
<li><strong>Easy to Test:</strong> Factories can facilitate testing. During unit testing, we can easily mock objects or swap real implementations with stubs.</li>
<li><strong>Code Reusability:</strong> Factories can be reused across different application parts, ensuring the same object creation logic is employed everywhere.</li></ul>
<p style="clear: both;">
To sum it up, the Factory Design Pattern is a potent tool for handling object creation in a versatile and maintainable manner. It is a widely embraced approach in software development, especially for managing object creation in intricate systems. Understanding and implementing this pattern can significantly enhance the design and maintainability of your code.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-22895279414077667662023-09-10T08:14:00.008+05:302023-12-18T01:06:45.570+05:30Thread-Safe Singleton Design Pattern in C#<p>In this post, we are going to discuss How to Implement <b>Thread-Safe Singleton Design Pattern in C#</b> with Examples. Please read our previous article where we discussed <a href="https://manish4dotnet.blogspot.com/2023/08/design-pattern-singleton-design-pattern.html" target="_blank">Singleton Design Pattern</a>. In that post, the way we have implemented the <a href="https://manish4dotnet.blogspot.com/2023/08/design-pattern-singleton-design-pattern.html" target="_blank">Singleton Design Pattern</a> is not Thread Safe in a Multithread Environment.</p>
<h2>Understand Thread-Safe in Singleton Design Pattern in C#.</h2>
<p>Before deep dive in to Thread-Safe Singleton Pattern, let us first see the problem that we face in a multithread environment if the <b>Singleton Class</b> is not Thread-Safe. Below is the <b>Singleton Class</b> which we have created in <a href="https://manish4dotnet.blogspot.com/2023/08/design-pattern-singleton-design-pattern.html" target="_blank">our last post</a>.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
/// <summary>
/// Sealed class to ensure that it cannot be inherited
/// </summary>
public sealed class Singleton
{
/// <summary>
/// To store the Singleton Instance
/// </summary>
private static Singleton instance = null;
/// <summary>
/// Counter value will be increment by 1 each time the object of the class is created
/// </summary>
private static int counter = 0;
/// <summary>
/// Private constructor to restrict the class to be instantiated from outside the class
/// </summary>
private Singleton()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
/// <summary>
/// Static Method to return the Singleton Instance
/// </summary>
public static Singleton Instance()
{
if (instance == null) { instance = new Singleton(); }
return instance;
}
/// <summary>
/// Method to accessed from outside of the class by using the Singleton Instance
/// </summary>
/// <param name="message"></param>
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
</pre>
<p>Let’s modify the <b>Program.cs</b> as follows to use multithread programming. As you can see in the below code, we are using Parallel.Invoke method and call <b>PrintCoachDetails()</b> and <b>PrintPlayerDetails()</b> methods parallelly.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
Parallel.Invoke(() => PrintCoachDetails(),
() => PrintPlayerDetails());
Console.ReadLine();
static void PrintCoachDetails()
{
//Thread-1 Calling the GetInstance() Method of the Singleton class
Singleton fromCoach = Singleton.Instance();
fromCoach.PrintDetails("From Coach");
}
static void PrintPlayerDetails()
{
//At the same time, Thread-2 also Calling the GetInstance() Method of the Singleton Class
Singleton fromPlayer = Singleton.Instance();
fromPlayer.PrintDetails("From Player");
}
</pre>
<p>So in above example, we are using the <b>Parallel.Invoke</b> method to access the <b>Instance() Method</b> parallelly. That means at the same time multiple threads are accessing the <b>Instance() Method</b>. The above code is not Thread-Safe because the way we have written the code here two different threads can evaluate the condition <b>if (instance == null)</b> at the same time and both threads found it to be true and they both will create the instances, which violates the singleton design pattern. So, now run the application and it will give you the following output.</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmuSLDOMJIGIbGkIDKqNzwVRs-Q1ym6f5gNLOpihtMALBAKIThRqUB_70J93PkRc53ScE1nED5ORsrA-bRA2HngXjbqy_omRVXqOlrnTJUnnrEKLyFW2C6mCYQHC3X9qYO3Ri80mnB0v_fFn3CFhgTgsiPieGR7XXu9gqmBqjJJtGVHoEfA7px_DDxjo0/s1600/Screenshot%202023-09-09%20192335.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="singleton design pattern" border="0" data-original-height="175" data-original-width="294" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmuSLDOMJIGIbGkIDKqNzwVRs-Q1ym6f5gNLOpihtMALBAKIThRqUB_70J93PkRc53ScE1nED5ORsrA-bRA2HngXjbqy_omRVXqOlrnTJUnnrEKLyFW2C6mCYQHC3X9qYO3Ri80mnB0v_fFn3CFhgTgsiPieGR7XXu9gqmBqjJJtGVHoEfA7px_DDxjo0/s1600/Screenshot%202023-09-09%20192335.png"/></a></div>
<p style="clear: both;">The above output clearly shows that the counter value has incremented to <b>2</b>, which proves that the constructor of the <b>Singleton class</b> is executed two times as a result two instances of the singleton class have been created. So, if the Singleton class is not Thread-Safe, then we may end up creating multiple instances of the Singleton class in a Multithread Environment.</p><a name='more'></a>
<h2>How to implement a Thread-Safe Singleton Design Pattern in C#?</h2>
<p>There are many ways, we can implement the Thread-Safe Singleton Design Pattern in C#. They are as follows.</p>
<ol>
<li>Thread-Safety Singleton Implementation using Lock.</li>
<li>Implementing Thread-Safety Singleton Design Pattern using Double-Check Locking.</li>
<li>Using Eager Loading to Implement Thread-Safety Singleton Design Pattern.</li>
<li>Using Lazy<T> Generic Class to Implement Lazy Loading in Singleton Design Pattern.</li>
</ol>
<p>Here we will discuss how to use Locks and Double-Check Locking Mechanisms to implement the <b>Thread-Safe Singleton Design Pattern</b> in C# which will create only one instance of the Singleton Class in a Multithread environment.</p>
<h2>Implementation of Thread-safe Singleton Design Pattern in C# using Locks</h2>
<p>Let us discuss how to implement the Thread-Safe Singleton Design Pattern in C# using locks.Using locks we can synchronize the method. So that only one thread can access it at any given point in time. For better understanding, please modify the Singleton Class as follows.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public sealed class SingletonUsingLock
{
/// <summary>
/// To store the Singleton Instance
/// </summary>
private static SingletonUsingLock instance = null;
/// <summary>
/// To use the lock, we need to create one variable
/// </summary>
private static readonly object Instancelock = new object();
/// <summary>
/// Counter value will be increment by 1 each time the object of the class is created
/// </summary>
private static int counter = 0;
/// <summary>
/// Private constructor to restrict the class to be instantiated from outside the class
/// </summary>
private SingletonUsingLock()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
/// <summary>
/// Static Method to return the Singleton Instance
/// </summary>
public static SingletonUsingLock Instance()
{
lock (Instancelock)
{
if (instance == null) { instance = new SingletonUsingLock(); }
}
return instance;
}
/// <summary>
/// Method to accessed from outside of the class by using the Singleton Instance
/// </summary>
/// <param name="message"></param>
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
</pre>
<p>In the above code, we lock the shared resource using the lock object and then check whether the instance is created or not.If the instance is already created then we simply return that instance else we will create the instance and then return that instance. The most important point that you need to remember is, as long as one thread locks the resource, no other thread can access the resource.Below is the modified <b>Program.cs</b> file:</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using SingletonPattern_ThreadSafe;
Parallel.Invoke(() => PrintCoachDetails(),
() => PrintPlayerDetails());
Console.ReadLine();
static void PrintCoachDetails()
{
//Thread-1 Calling the Instance() Method of the Singleton class
SingletonUsingLock fromCoach = SingletonUsingLock.Instance();
fromCoach.PrintDetails("From Coach");
}
static void PrintPlayerDetails()
{
//At the same time, Thread-2 also Calling the Instance() Method of the Singleton Class
SingletonUsingLock fromPlayer = SingletonUsingLock.Instance();
fromPlayer.PrintDetails("From Player");
}
</pre>
<p>Now run the application and you will get the following output.</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkK0x1YhxER3MOp8d71RsRSYiSsKq2qFWYr_ZQfBqezu3v-BIpsy9Js78MTUmIXWAYPfRCyyi-11g4_ngDz72iQSrn9-6vcG9jO9NV43wwUDtqvgCxnW6Tl_7GX22hEAKriyOBXzx-tgeTf6jgMUYPrHfwI_n6Gh5f8jCXpltdRbul4Yx2sD8GYXJMWTA/s1600/Screenshot%202023-09-09%20203003.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="Thread-safe Singleton Design Pattern in C# using Locks" border="0" data-original-height="154" data-original-width="242" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkK0x1YhxER3MOp8d71RsRSYiSsKq2qFWYr_ZQfBqezu3v-BIpsy9Js78MTUmIXWAYPfRCyyi-11g4_ngDz72iQSrn9-6vcG9jO9NV43wwUDtqvgCxnW6Tl_7GX22hEAKriyOBXzx-tgeTf6jgMUYPrHfwI_n6Gh5f8jCXpltdRbul4Yx2sD8GYXJMWTA/s1600/Screenshot%202023-09-09%20203003.png"/></a></div>
<p style="clear: both;">The above code implementation using lock solves the <a href="https://manish4dotnet.blogspot.com/2023/08/design-pattern-singleton-design-pattern.html" target="_blank">Singleton Design Pattern</a> Thread-Safe issues in a multithreading environment. But the problem is that it is slow down your application as only one thread can access the GetInstance method at any given point in time. We can overcome the above problem by using the <b>Double-Checked Locking</b> mechanism.</p>
<h2>Implement Thread-Safe Singleton Design Pattern using Double checked locking</h2>
<p>In the <b>Double-Checked Locking</b> implementation for <b>Thread-Safe Singleton Design Pattern</b> in C#, first, we will check whether the instance is created or not. If not then only we will synchronize the method using the lock. For a better understanding, please modify the Singleton class as follows.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
public sealed class SingletonUsingDoubleLock
{
/// <summary>
/// To store the Singleton Instance
/// </summary>
private static SingletonUsingDoubleLock instance = null;
/// <summary>
/// To use the lock, we need to create one variable
/// </summary>
private static readonly object Instancelock = new object();
/// <summary>
/// Counter value will be increment by 1 each time the object of the class is created
/// </summary>
private static int counter = 0;
/// <summary>
/// Private constructor to restrict the class to be instantiated from outside the class
/// </summary>
private SingletonUsingDoubleLock()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
/// <summary>
/// Static Method to return the Singleton Instance
/// </summary>
public static SingletonUsingDoubleLock Instance()
{
if (instance == null)
{
lock (Instancelock)
{
if (instance == null) { instance = new SingletonUsingDoubleLock(); }
}
}
return instance;
}
/// <summary>
/// Method to accessed from outside of the class by using the Singleton Instance
/// </summary>
/// <param name="message"></param>
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
</pre>
<p>In the above code, we are checking the instance two times whether it is null or not. If it is not null, then we are returning the Singleton instance. If it is null, then we are using the lock to make sure only one thread can enter the critical section. And within the lock block, again we are checking the null condition to make sure only one instance of the Singleton Class is going to be created.</p>
<p>Now run the application and you will see the output as expected as shown in the below image.</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkK0x1YhxER3MOp8d71RsRSYiSsKq2qFWYr_ZQfBqezu3v-BIpsy9Js78MTUmIXWAYPfRCyyi-11g4_ngDz72iQSrn9-6vcG9jO9NV43wwUDtqvgCxnW6Tl_7GX22hEAKriyOBXzx-tgeTf6jgMUYPrHfwI_n6Gh5f8jCXpltdRbul4Yx2sD8GYXJMWTA/s1600/Screenshot%202023-09-09%20203003.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="Thread-safe Singleton Design Pattern in C# using Locks" border="0" data-original-height="154" data-original-width="242" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkK0x1YhxER3MOp8d71RsRSYiSsKq2qFWYr_ZQfBqezu3v-BIpsy9Js78MTUmIXWAYPfRCyyi-11g4_ngDz72iQSrn9-6vcG9jO9NV43wwUDtqvgCxnW6Tl_7GX22hEAKriyOBXzx-tgeTf6jgMUYPrHfwI_n6Gh5f8jCXpltdRbul4Yx2sD8GYXJMWTA/s1600/Screenshot%202023-09-09%20203003.png"/></a></div>
<p style="clear: both;">The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>
Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-67969690578082813652023-08-31T05:57:00.008+05:302023-12-18T01:06:58.417+05:30Singleton Design Pattern in C#<p>The Singleton design pattern stands as one of the most commonly used creation patterns in software development. It guarantees that a class exists in only one instance and grants a universal way to reach that instance. This proves especially handy when aiming to establish a singular hub of control or coordination within your application. Let's explore the Singleton pattern through a practical C# example.</p>
<h2>What is Singleton Pattern?</h2>
<p>We need to use the Singleton Design Pattern in C# when we need to ensure that only one instance of a particular class is going to be created and then provide simple global access to that instance for the entire application. This pattern becomes invaluable when handling resources like database connections, thread pools, configuration settings, and more—minus the complication of creating numerous instances.</p>
<h2>Implementation Guidelines of Singleton Design Pattern</h2>
<p>Following are the guidelines to implement the Singleton Design Pattern</p>
<ol>
<li>Declare a constructor that should be <b>private</b> and <b>parameterless</b>. This is required to restrict the class to be instantiated from outside the class.</li>
<li>The class should be declared as <b>sealed</b> which will ensure that it cannot be inherited.</li>
<li>We need to create a <b>private static </b>variable that is going to hold a reference to the singleton instance of the class.</li>
<li>We also need to create a public static <b>property/method</b> which will return the singleton instance of the class.</li>
</ol>
<h2>Implement the Singleton Pattern in C#</h2>
<p>There are many ways, we can implement the Singleton Design Pattern in C#. They are as follows.</p>
<ol>
<li>No Thread-Safe Singleton Design Pattern</li>
<li>Thread-Safety Singleton Implementation using Lock.</li>
<li>Implementing Thread-Safety Singleton Design Pattern using Double-Check Locking.</li>
<li>Using Eager Loading to Implement Thread-Safety Singleton Design Pattern.</li>
<li>Using Lazy<T> Generic Class to Implement Lazy Loading in Singleton Design Pattern.</li>
</ol>
<a name='more'></a>
<h2>No Thread-Safe Singleton Design Pattern</h2>
<p>Let us understand how to implement the No Thread Safe Singleton Design Pattern in C# with an Example. First, create a class file with the name Singleton.cs and then copy and paste the following code into it.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
/// <summary>
/// Sealed class to ensure that it cannot be inherited
/// </summary>
public sealed class Singleton
{
/// <summary>
/// To store the Singleton Instance
/// </summary>
private static Singleton instance = null;
/// <summary>
/// Counter value will be increment by 1 each time the object of the class is created
/// </summary>
private static int counter = 0;
/// <summary>
/// Private constructor to restrict the class to be instantiated from outside the class
/// </summary>
private Singleton()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
/// <summary>
/// Static Method to return the Singleton Instance
/// </summary>
public static Singleton Instance()
{
if (instance == null) { instance = new Singleton(); }
return instance;
}
/// <summary>
/// Method to accessed from outside of the class by using the Singleton Instance
/// </summary>
/// <param name="message"></param>
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
</pre>
<h2>Breaking the above Singleton.cs class code</h2>
<ol>
<li>We created the Singleton class as sealed which ensures that the class cannot be inherited from the derived classes.</li>
<li>Created with a <b>private parameterless</b> constructor which will ensure that the class is not going to be instantiated from outside the class.</li>
<li>We declared the instance variable as private and also initialized it with the null value which ensures that only one instance of the class is going to be created based on the null condition.</li>
<li>The public method <b>Instance()</b> is used to return only one instance of the class by checking the value of the private variable instance.</li>
<li>The public method PrintDetails can be invoked from outside the class through the singleton instance.</li>
</ol>
<p>Let us see how we can use the above Singleton class in our <b>Program.cs</b> class. So, modify the the <b>Program.cs</b> class as follows. As you can see in the below code, we are calling the <b>Instance()</b> static method of the <b>Singleton class</b> which will return the Singleton instance, and then using that <b>Singleton instance</b> we are calling the <b>PrintDetails</b>. We are doing this two times.</p>
<pre class="brush:csharp;class-name: 'divSyntax'" style="text-align: left;">
using SingletonPatternExample;
Singleton fromCoach = Singleton.Instance();
fromCoach.PrintDetails("From Coach");
Singleton fromPlayer = Singleton.Instance();
fromPlayer.PrintDetails("From Player");
Console.ReadLine();
</pre>
<p>Run the application and it will give you the following output.</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSLUC10kNMBRFetGomycYh7Xv7g7B3_q9h6prGVKcU7V04-ytiCrxLUZGXWE1LTeQZG1tfnxc_gy0DOemPHepHxpPeGRaf-jjIXkmo_jQFDYuS8x6VvnZAhICXzBA8pLmoAEGInwEWesg7-mKsUSWeYUtzdtPzl2TwG8Z5N7Q4CkX_iz-TWQDmwmQ0f5A/s1600/Screenshot%202023-08-30%20181109.png" style="display: block; padding: 1em 0; text-align: center; clear: left; float: left;"><img alt="singleton design pattern" border="0" data-original-height="182" data-original-width="455" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSLUC10kNMBRFetGomycYh7Xv7g7B3_q9h6prGVKcU7V04-ytiCrxLUZGXWE1LTeQZG1tfnxc_gy0DOemPHepHxpPeGRaf-jjIXkmo_jQFDYuS8x6VvnZAhICXzBA8pLmoAEGInwEWesg7-mKsUSWeYUtzdtPzl2TwG8Z5N7Q4CkX_iz-TWQDmwmQ0f5A/s1600/Screenshot%202023-08-30%20181109.png"/></a></div>
<p style="clear: both;">As you can see in the above output, it clearly shows that the private constructor is executed only once even though we have called the <b>Instance()</b> method twice and printed the counter value as 1. Hence it proves that the singleton instance is created only once. </p>
<h2>Wrapping Up</h2>
<p>The Singleton design pattern assures a class's singular existence and opens a worldwide gateway to this instance. This pattern becomes a valuable asset in scenarios necessitating resource management or a single locus of control. By embracing the Singleton pattern in C#—as illustrated by this example—you can effortlessly produce efficient and thread-safe singleton classes in your applications.</p>
<p>We will discuss the <a href="https://manish4dotnet.blogspot.com/2023/09/design-pattern-thread-safe-singleton.html" target="_blank">Thread Safe Singleton implementations</a> in upcoming articles.</p>
<p>The full source code is available here:</p>
<p><a href="https://github.com/MDubey87/DesignPatterns" target="_blank"><div class="separator" style="clear: both;"><img alt="" border="0" width="150" data-original-height="57" data-original-width="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png"/></div></a></p>
<p>Happy coding!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0tag:blogger.com,1999:blog-1563380748301069004.post-76006181219710806452023-08-23T08:49:00.013+05:302024-03-24T23:54:15.140+05:30Design Patterns: Building Robust and Flexible Software<h2>What Are Design Patterns?</h2>
<p>At their core, design patterns are proven solutions to recurring design problems. They offer developers a common vocabulary and a set of guidelines to approach and tackle issues that frequently arise during software development. These patterns are not specific to a particular programming language or framework; rather, they provide general templates that can be adapted to different contexts.</p>
<h2>Why Do Design Patterns Matter?</h2>
<b>1.Code Reusability:</b> Design patterns encapsulate solutions to common problems. By using these patterns, developers can reuse tried-and-tested solutions, saving time and reducing the likelihood of bugs.
<br /><br />
<b>2.Scalability and Maintainability:</b> Implementing design patterns leads to cleaner, more organized code that is easier to understand and maintain. This is crucial as projects grow in complexity.
<br /><br />
<b>3.Communication:</b> Design patterns offer a common language for developers to discuss and document solutions. This leads to better collaboration within teams and across different projects.
<br /><br />
<b>4.Flexibility:</b> Design patterns promote loosely coupled components, allowing you to swap out parts of your system without causing cascading changes.
<br /><br /><a name='more'></a>
<h2>Common Design Patterns:</h2>
<b>1.Creational Patterns:</b> These patterns focus on object creation mechanisms, helping manage the process of object instantiation.<ul style="text-align: left;">
<li><a href="https://manish4dotnet.blogspot.com/2023/08/design-pattern-singleton-design-pattern.html" target="_blank">Singleton</a>: Ensures a class has only one instance and provides a global point of access to it.</li>
<li><a href="https://manish4dotnet.blogspot.com/2023/10/design-pattern-factory-design-pattern.html" target="_blank">Factory Method</a>: Defines an interface for creating objects but lets subclasses decide which class to instantiate.</li>
<li><a href="https://manish4dotnet.blogspot.com/2023/11/design-pattern-abstract-factory-design.html" target="_blank">Abstract Factory Method</a>: Allows us to create a Factory for factory classes.</li>
<li><a href="https://manish4dotnet.blogspot.com/2023/12/design-pattern-builder-design-pattern.html%22" target="_blank">Builder</a>: Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.</li>
<li><a href="https://manish4dotnet.blogspot.com/2023/12/design-pattern-creational-pattern.html" target="_blank">Prototype</a>: Creating a new object instance from another similar instance and then modify according to our requirements.</li>
</ul>
<b>2.Structural Patterns:</b> These patterns deal with the composition of classes and objects to form larger structures.
<ul style="text-align: left;">
<li><a href="https://manish4dotnet.blogspot.com/2023/12/adapter-design-pattern-in-c.html" target="_blank">Adapter</a>: Allows incompatible interfaces to work together by providing a wrapper that converts one interface into another.</li>
<li><a href="https://manish4dotnet.blogspot.com/2024/01/decorator-design-pattern-in-c.html" target="_blank">Decorator</a>: Adds behavior to objects dynamically, without altering their structure.</li>
<li><a href="https://manish4dotnet.blogspot.com/2024/01/facade-design-pattern-in-c.html" target="_blank">Facade</a>: Provides a unified interface to a set of interfaces in a subsystem, simplifying interaction for clients.</li>
<li><a href="https://manish4dotnet.blogspot.com/2024/01/composite-design-pattern-in-c.html" target="_blank">Composite:</a> Used when we have to implement a part-whole hierarchy. For example, a diagram made of other pieces such as circle, square, triangle, etc.</li>
<li><a href="https://manish4dotnet.blogspot.com/2024/01/proxy-design-pattern-in-c.html" target="_blank">Proxy:</a> Provide a surrogate or placeholder for another object to control access to it.</li>
<li><a href="https://manish4dotnet.blogspot.com/2024/01/flyweight-design-pattern-in-c.html" target="_blank">Flyweight:</a> Caching and reusing object instances, used with immutable objects. For example, string pool.</li>
<li><a href="https://manish4dotnet.blogspot.com/2024/01/bridge-design-pattern-in-c.html" target="_blank">Bridge:</a> The bridge design pattern is used to decouple the interfaces from implementation and hiding the implementation details from the client program.</li>
</ul>
<b>3.Behavioral Patterns:</b> These patterns focus on communication between objects and responsibilities within an object.
<ul style="text-align: left;">
<li><a href="https://manish4dotnet.blogspot.com/2024/03/observer-design-pattern-in-c.html" target="_blank">Observer:</a> Defines a dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.</li>
<li>Strategy: Defines a family of algorithms, encapsulates each one, and makes them interchangeable.</li>
<li>Command: Turns a request into a stand-alone object, containing all the information about the request.</li>
<li>Template Method: Used to create a template method stub and defer some of the steps of implementation to the subclasses.</li>
<li>Mediator: Used to provide a centralized communication medium between different objects in a system.</li>
<li>Chain of Responsibility: Used to achieve loose coupling in software design where a request from the client is passed to a chain of objects to process them.</li>
<li>State: State design pattern is used when an Object change it’s behavior based on it’s internal state.</li>
<li>Visitor: Visitor pattern is used when we have to perform an operation on a group of similar kind of Objects.</li>
<li>Interpreter: Defines a grammatical representation for a language and provides an interpreter to deal with this grammar.</li>
<li>Iterator: Used to provide a standard way to traverse through a group of Objects.</li>
<li>Memento: The memento design pattern is used when we want to save the state of an object so that we can restore later on.</li>
</ul>
<br />
<h2>Final Thoughts</h2>
<p>Design patterns are not just about writing better code; they're about cultivating a mindset that prioritizes maintainability, flexibility, and collaboration. By integrating these patterns into your development process, you empower yourself to build software that can stand the test of time and adapt to changing requirements.</p>
<p>As you dive into the world of design patterns, remember that choosing the right pattern for the right situation is an art. Each pattern has its strengths and weaknesses, and understanding their nuances is key to effective implementation. So, whether you're facing the challenges of object creation, system structuring, or communication between components, design patterns offer a treasure trove of solutions waiting to be explored.</p>
<p>Happy learning!! 😊</p>Manishhttp://www.blogger.com/profile/07340495073591888692noreply@blogger.com0