Category: designPatterns

Pattern: CompositeProvider

Description

Composite Provider pattern is a structural design pattern that lets you compose objects into tree structures to represent part-whole hierarchies.
Composite lets clients treat individual objects and compositions of objects uniformly.

Example in .NET :

CompositeProvider

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using Microsoft.Extensions.FileProviders;
 
namespace CompositeProvider;
public class CompositeProviderDemo
{
    private readonly IFileProvider _fileProvider;
    public CompositeProviderDemo(string folder)
    {
        var fileOnHDDProvider = new PhysicalFileProvider(folder);
        var manifestEmbeddedProvider =
    new ManifestEmbeddedFileProvider(this.GetType().Assembly);
        _fileProvider = new CompositeFileProvider(fileOnHDDProvider,manifestEmbeddedProvider);
 
    }
    public string[] GetFiles()
    {
        List<string> ret = [];
        var files = _fileProvider.GetDirectoryContents(string.Empty);
        var contents = _fileProvider.GetDirectoryContents(string.Empty);
        foreach (var fileInfo in contents)
        {
            ret.Add(fileInfo.Name);
        }
        return ret.ToArray();
    }
    public string GetContentFile(string name)
    {
        var fileInfo = _fileProvider.GetFileInfo(name);
        if (fileInfo.Exists)
        {
            using var stream = fileInfo.CreateReadStream();
            using var reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }
        return string.Empty;
    }
 
}

And his usage

01
02
03
04
05
06
07
08
09
10
11
12
13
14
// See https://aka.ms/new-console-template for more information
using CompositeProvider;
 
Console.WriteLine("Hello, World!");
var path = Directory.GetParent(Environment.CurrentDirectory);
ArgumentNullException.ThrowIfNull(path);
CompositeProviderDemo compositeProvider = new(path.FullName) ;
Console.WriteLine("Files in the current directory:");
foreach (var file in compositeProvider.GetFiles())
{
    Console.WriteLine(file);
}
Console.WriteLine("obtain MyResource.txt even if does not exists on folder");
Console.WriteLine(compositeProvider.GetContentFile("MyResource.txt"));

Learn More

Source Code for Microsoft implementation of CompositeProvider SourceCode Composite Provider
Learn More File Providers in ASP.NET Core
Wikipedia
}

Homework

Imagine that you have 2 loggers , for a file and a console.
Implement a composite provider that allows you to log to multiple destinations at the same time.

Pattern: AbstractFactory

Description

Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.

Example in .NET :

AbstractFactory

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
using Microsoft.Data.SqlClient;
using System.Data.Common;
 
namespace AbstractFactory;
internal class AbstractFactoryDemo
{
    public static void Demo()
    {
        //create DbConnection factory by using the instance of SqlConnection
        DbConnection connection = new SqlConnection();
        //create DbCommand instance by using the instance of SqlConnection
        DbCommand command = connection.CreateCommand();
        //really, the DBCommand is a SqlCommand
        SqlCommand? sqlCommand = command as SqlCommand;
        //check if the DbCommand is a SqlCommand
        Console.WriteLine($"DbCommand is SqlCommand: {sqlCommand != null}");
    }
}

Learn More

Source Code for Microsoft implementation of AbstractFactory

SourceCode DbConnection

Learn More

Wikipedia

}

Homework

Imagine you want to produce loggers. You have a logger that logs to a file and a logger that logs to a console and a Nothing Logger – a logger that does nothing. Implement an abstract factory that will allow you to create a logger factory that will create a logger that logs to a file or to a console or nothing.

Pattern: Flyweight

Description

Flyweight pattern is used to reduce the memory and resource usage for complex models containing a large number of similar objects.

Example in .NET :

Flyweight

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
using System.Text;
 
namespace Flyweight;
internal class FlyweightDemo
{
    public static void Demo()
    {
        var str = "Andrei Ignat";
        var str2 = string.Intern(str);
        var str3 = new StringBuilder("Andrei").Append(" Ignat").ToString();
        Console.WriteLine($"str == str2: Value {str==str2} Reference {Object.ReferenceEquals(str,str2)}");
        Console.WriteLine($"str == str3: Value {str==str3} Reference {Object.ReferenceEquals(str,str3)}");
 
    }
}

Learn More

Source Code for Microsoft implementation of Flyweight

SourceCode String.Intern

Learn More

Wikipedia

}

Homework

Make an exchange rate system. The symbol and names of the currency are the same for all the currencies. The exchange rate is different for each currency. Implement a flyweight that will allow you to create a currency with a symbol and a name and to get the exchange rate for the currency.

Pattern: Observer

Description

Observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Example in .NET :

Observer

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System.ComponentModel;
using System.Runtime.CompilerServices;
 
namespace Observer;
 
/// <summary>
/// INotifyPropertyChanged is an interface that provides a mechanism for the object to notify clients that a property value has changed.
/// </summary>
public class Person: INotifyPropertyChanged
{
    private string name=string.Empty;
    public string Name
    {
        get => name;
        set
        {
            if (name == value) return;
            name = value;
            OnPropertyChanged();
        }
    }
 
    public event PropertyChangedEventHandler? PropertyChanged;
 
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
internal class ObserverDemo
{
    public static void Demo()
    {
        Person person = new ();
        //subscribe to the event to observe the changes
        person.PropertyChanged += (sender, args) =>
        {
            var p = sender as Person;
            Console.WriteLine($"Property {args.PropertyName} changed to {p?.Name}");
        };
        person.Name = "Andrei Ignat" ;
    }
}

Learn More

Source Code for Microsoft implementation of Observer

SourceCode INotifyPropertyChanged

Learn More

Wikipedia

}

Homework

Imagine you have a logger that logs to a file and to a console. Implement an observable logger that will allow you to subscribe to the logger and to be notified when the logger logs a message.

Pattern: FluentInterface

Description

Fluent interface allows you do have method chaining

Example in .NET :

FluentInterface

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using Microsoft.Extensions.DependencyInjection;
using System.Data;
using System.Data.Common;
 
namespace FluentInterface;
internal static class FluentInterfaceDemo
{
    public static ServiceCollection AddServices(this ServiceCollection sc)
    {
        //just for demo, does not make sense
        sc
            .AddSingleton<IComparable>((sp) =>
            {
                //does not matter
                return 1970;
            })
            .AddSingleton<IComparable<Int32>>((sp) =>
            {
                //does not matter
                return 16;
            });
        //this way you can chain the calls , making a fluent interface
        return sc;
 
 
    }
}

Learn More

Source Code for Microsoft implementation of FluentInterface

SourceCode Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton

Learn More

Wikipedia

}

Homework

Implement a class person that you can see the first name and last name as fluent interface

Pattern: IOC

Description

Inversion of Control is a principle in software engineering by which the control of objects or portions of a program is transferred to a container or framework. It’s a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework.

Examples in .NET :

IOC

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
namespace IOC;
public class NotificationService
{
    private readonly IMessageService _messageService;
 
    public NotificationService(IMessageService messageService)
    {
        _messageService = messageService;
    }
 
    public void SendNotification(string message)
    {
        _messageService.SendMessage(message);
    }
}
public interface IMessageService
{
    void SendMessage(string message);
}

DI

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
namespace IOC;
public class SMSService : IMessageService
{
    public void SendMessage(string message)
    {
        Console.WriteLine("Sending SMS: " + message);
    }
}
 
public class EmailService : IMessageService
{
    public void SendMessage(string message)
    {
        Console.WriteLine("Sending email: " + message);
    }
}

Learn More

Source Code for Microsoft implementation of IOC

SourceCode ServiceCollection

Learn More

dofactory
DPH

}

Homework

Implement a simple IoC container that will allow you to register and resolve dependencies. The container should be able to resolve dependencies by type and by name.

Pattern: Lazy

Description

Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.

Example in .NET :

Lazy

01
02
03
04
05
06
07
08
09
10
11
namespace Lazy;
internal class LazyDemo
{
    public DateTime dateTimeConstructClass =DateTime.Now;
     
    public Lazy<DateTime> DateTimeLazy = new(() =>
    {
        Console.WriteLine("Lazy<DateTime> is being initialized ONCE!");
        return DateTime.Now;
    });
}

Learn More

Source Code for Microsoft implementation of Lazy

SourceCode Lazy

Learn More

C2Wiki
Wikipedia

Homework

Implement a lazy initialization of a logger that logs to a file and to a console. The logger should be created only when it is needed.

Pattern: Chain

Description

Chain of responsibility pattern allows an object to send a command without knowing what object will receive and handle it. Chain the receiving objects and pass the request along the chain until an object handles it

Example in .NET :

Chain

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
namespace Chain;
 
public static class ChainDemo
{
    public static int SecondException()
    {
        try
        {
            FirstException();
            return 5;
        }
        catch (Exception ex)
        {
            throw new Exception($"from {nameof(SecondException)}", ex);
        }
    }
    static int FirstException()
    {
        throw new ArgumentException("argument");
    }
}

Learn More

Wikipedia

Homework

Implement a middleware in ASP.NET Core that intercepts the exception and logs it to the database. The middleware should be able to pass the exception to the next middleware in the chain.

Pattern: Decorator

Description

Decorator allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

Example in .NET :

Decorator

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace Decorator;
internal class DecoratorDemo
{
    public static void Stream_Crypto_Gzip()
    {
        string nameFile = "test.txt";
        if (File.Exists(nameFile))
            File.Delete(nameFile);
        byte[] data = ASCIIEncoding.ASCII.GetBytes("Hello World!");
        //first time we have a stream
        using (var stream = new FileStream(nameFile, FileMode.OpenOrCreate, FileAccess.Write))
        {
            //stream.Write(data, 0, data.Length);
            //return;
             
            var cryptic = new DESCryptoServiceProvider();
 
            cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
            //we decorate the initial stream with a crypto stream
            using (var crStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write))
            {
                //and we decorate further by encoding
                using (var gz = new GZipStream(crStream, CompressionLevel.Optimal))
                {
                    gz.Write(data, 0, data.Length);
                }
 
            }
        }
    }
}

Learn More

Wikipedia

Homework

1. Add a logging to DBConnection . 2. Use by decorating a coffee with milk, sugar, and chocolate (and maybe other condiments). The coffee should be able to display the condiments in a Display method and calculate the price of the coffee with milk, sugar, and chocolate.

Pattern: Facade

Description

Facade is is an object that provides a simplified interface to a larger body of code, such as a class library.

Example in .NET :

Facade

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
 
namespace Facade;
internal class FacadeDemo
{
    public static void ExecuteSql()
    {
        MyDbContext cnt = new();
        //calling the facade
        DatabaseFacade dbFacade = cnt.Database;
        dbFacade.EnsureCreated();
    }
}
 
public class MyDbContext:DbContext
{
     
}

Learn More

Wikipedia

Homework

Implement a Facade that will allow you to display a question in a MessageBox with a single method call in a console application and return yes/no as a result.

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.