Category: designPatterns

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


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

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


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


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

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


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

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

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

   

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

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.

Pattern: Factory

Description

A factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be new

Example in .NET :

Factory

 
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Internal;
using System.Data.Common;
using System.Globalization;
using System.Net;
using System.Web.Mvc;

namespace Factory;
internal class FactoryDemo
{
    public static void DemoWebRequest()
    {
        HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create("http://www.yahoo.com");

    }
    public static void DemoConvert()
    {
        string value = "1,500";
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");

        Console.WriteLine(Convert.ToDouble(value));

        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
        Console.WriteLine(Convert.ToDouble(value));

    }
    static void RegisterControllerFactory()
    {
        ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
    }
}

//default controller factory is a factory of controllers
class MyControllerFactory : System.Web.Mvc.DefaultControllerFactory
{

    public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
    {
        if (controllerName == "andrei")
            return null;//maybe controller not found

        return base.CreateController(requestContext, controllerName);
    }
}
    

     

Learn More

Wikipedia

Homework

having multiple types of drinks( water, tea, coffee) with an IDrink interface create a factory method ( with a parameter ) to create a drink

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.