diff --git a/.vscode/settings.json b/.vscode/settings.json index 3f7eefa..b55f5c4 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -5,7 +5,7 @@ { "match": "\\.md$", "notMatch": "README\\.md$", - "cmd": "marp ${fileDirname}\\${fileBasename} -o ${fileDirname}\\${fileBasenameNoExt}-slides.html --html true", + "cmd": "marp \"${fileDirname}\\${fileBasename}\" -o \"${fileDirname}\\${fileBasenameNoExt}-slides.html\" --html true", "useShortcut": false, "silent": false }, diff --git a/15. Design Patterns in C#-slides.html b/15. Design Patterns in C#-slides.html new file mode 100644 index 0000000..5e71d80 --- /dev/null +++ b/15. Design Patterns in C#-slides.html @@ -0,0 +1,167 @@ +15. Design Patterns in C#
+

Design Patterns in C#

+
+
+

Overview

+
    +
  • The Singleton Pattern
  • +
  • Dependency Injection
  • +
+
+
+

The Singleton Pattern

+
+
+

The problem

+
    +
  • In most cases, it makes no sense to create an instance of a class every time its members need to be accessed +
      +
    • For example, a shared resource manager that is being called from multiple classes
    • +
    +
  • +
  • While a static class could be used for this, there are some problems: +
      +
    • As stated in lecture 10, static classes can only have static members
    • +
    • Static classes cannot be instantiated, so a reference to them cannot be passed around as a parameter
    • +
    • Static classes cannot inherit from other classes or implement interfaces
    • +
    • And many more...
    • +
    +
  • +
+
+
+

The solution

+
    +
  • The singleton class is a class that benefits from all the perks of a non-static class (non-static members, inheritance, referencing…), but only one (or zero) instances of it ever exists during the lifetime of your application
  • +
  • For example, reading from / writing to a file that should be accessible to multiple clients, should be made into a singleton +
      +
    • Instead of every client directly accessing the same file (and possibly causing massive performance issues), the singleton is instantiated once and a reference to it is provided to clients
    • +
    • The singleton could take care of queueing the read/write requests and be the only entity accessing the actual file
    • +
    +
  • +
+
+
+

A singleton implementation could look something like this:

+
+
+
class Singleton
+{
+  private static Singleton instance = null;
+
+  private Singleton() { }
+  public void MySingletonFunction()
+  {
+    Console.WriteLine
+      ("This function is accessible anywhere!");
+  }
+
+  public static Singleton Instance
+  {
+    get
+    {
+      if (instance == null)
+        instance = new Singleton();
+      return instance;
+    }
+  }
+}
+
+
+
+

+class Program
+{
+  static void Main(string[] args)
+  {
+    Singleton.Instance.MySingletonFunction();
+    // Outputs: "This function is accessible
+    // from everywhere!"
+  }
+}
+
+
+
+
+
+

Implementing a singleton pattern

+
    +
  • The exact implementation of the singleton is out of the scope of this course, but it is important to understand that it exists and what its purpose is
  • +
  • Multitude of examples for different use cases are available and can be found by googling
  • +
+
+
+

Dependency Injection

+
+
+

The problem

+
    +
  • Traditionally, when new objects of classes are instantiated, the consuming class handles the creation of the objects
  • +
  • Many classes change their functionality throughout the development of any project +
      +
    • This means that also every single consuming class has to change
    • +
    • This is called tight coupling
    • +
    +
  • +
+
+
+

The solution

+
    +
  • What if, instead of directly creating the objects, they were provided by some interface that takes care of the creation?
  • +
  • This way, even if the base class changes, the consuming classes won't care because they only know about the provider
  • +
  • This provider is called Container, and the functionality being injected is called Service
  • +
  • In ASP.NET, this container system is built in
  • +
+
+
+

Dependency injection in ASP.NET

+
public class HomeController : Controller
+{
+  private readonly IUserRepository _userRepository;
+
+  public HomeController(IUserRepository userRepository)
+  {
+    _userRepository = userRepository;
+  }
+  // User repository including all users is now accessible in HomeController
+}
+
+
+
+

Design Patterns

+
    +
  • +

    If the concepts of a singleton and dependency injection flew over your head, don't worry about it

    +
  • +
  • +

    The important thing is to know they exist so that when they come up again in ASP.NET, you have already familiarized yourself with the terms

    +
      +
    • Thus, understanding the logic behind ASP.NET becomes less overwhelming
    • +
    +
  • +
  • +

    There are many more design patterns, see the material here

    +
    public void ConfigureServices(IServiceCollection services)
    +{
    +  services.AddSingleton<IDateTime, SystemDateTime>();
    +  services.AddControllersWithViews();
    +}
    +
    +
  • +
+
+
\ No newline at end of file diff --git a/15. Design Patterns in C#.md b/15. Design Patterns in C#.md index 0fd1dd7..d9897c7 100644 --- a/15. Design Patterns in C#.md +++ b/15. Design Patterns in C#.md @@ -1,133 +1,137 @@ -# Design Patterns in C# +--- +marp: true +paginate: true +math: mathjax +theme: buutti +title: 15. Design Patterns in C# +--- -![](imgs/15%20Design%20Patterns%20in%20C%23_0.png) +# Design Patterns in C# ---- + + -# Overview +## Overview -The Singleton Pattern +* The Singleton Pattern +* Dependency Injection -Dependency Injection +## The Singleton Pattern -# The Singleton Pattern +### The problem -* In some cases, it would make no sense to create an instance of a class every time it's members need to be accessed +* In most cases, it makes no sense to create an instance of a class every time its members need to be accessed * For example, a shared resource manager that is being called from multiple classes * While a static class could be used for this, there are some problems: - * As stated in the previous slide, static classes can only have static members + * As stated in [lecture 10](10.%20Static%20Members,%20Methods%20and%20Classes.md#StaticClasses), static classes can only have static members * Static classes cannot be instantiated, so a reference to them cannot be passed around as a parameter * Static classes cannot inherit from other classes or implement interfaces * [And many more... ](https://www.c-sharpcorner.com/UploadFile/akkiraju/singleton-vs-static-classes/) -# The Singleton Pattern (continued) +### The solution -* The __singleton __ class is a class that benefits from all the perks of a non-static class (non-static members, inheritance, referencing…), but only one (or zero) instances of it ever exists during the lifetime of your application +* The __singleton__ class is a class that benefits from all the perks of a non-static class (non-static members, inheritance, referencing…), but only one (or zero) instances of it ever exists during the lifetime of your application * For example, reading from / writing to a file that should be accessible to multiple clients, should be made into a singleton * Instead of every client directly accessing the same file (and possibly causing massive performance issues), the singleton is instantiated once and a reference to it is provided to clients * The singleton could take care of queueing the read/write requests and be the only entity accessing the actual file -A singleton implementation could look something like this: - -class Singleton - -{ - -private static Singleton instance = null; - -private Singleton() { } - -public void MySingletonFunction() - -{ - -Console.WriteLine - -("This function is accessible from everywhere!"); - -} - -public static Singleton Instance - -{ - -get - -{ - -if (instance == null) - -instance = new Singleton(); - -return instance; - -} +--- -} +A singleton implementation could look something like this: -} +
+
+ + ```csharp + class Singleton + { + private static Singleton instance = null; + + private Singleton() { } + public void MySingletonFunction() + { + Console.WriteLine + ("This function is accessible anywhere!"); + } + + public static Singleton Instance + { + get + { + if (instance == null) + instance = new Singleton(); + return instance; + } + } + } + ``` +
+
+ +```csharp class Program - -{ - -static void Main(string[] args) - { - -Singleton.Instance.MySingletonFunction(); - -// Outputs "This function is accessible from everywhere!" - + static void Main(string[] args) + { + Singleton.Instance.MySingletonFunction(); + // Outputs: "This function is accessible + // from everywhere!" + } } +``` +
+
-} -The exact implementation of the singleton is out of the scope of this course, but it is important to understand that it exists and what its purpose is +### Implementing a singleton pattern + +* The exact implementation of the singleton is out of the scope of this course, but it is important to understand that it exists and what its purpose is +* Multitude of examples for different use cases are available and can be found by googling -Multitude of examples for different use cases are available and can be found by googling +## Dependency Injection -# Dependency Injection +### The problem * Traditionally, when new objects of classes are instantiated, the consuming class handles the creation of the objects -* A lot of classes change their functionality throughout the development of any project +* Many classes change their functionality throughout the development of any project * This means that also _every single_ consuming class has to change - * This is called __"tight coupling"__ -* What if, instead of directly creating the objects, they were provided by some interface that takes care of the creation? - * This way, even if the base class changes, the consuming classes won't care because they only know about the provider - * This provider is called __Container, __ and the functionality being injected is called __Service__ - * In ASP.NET, this container system is built in ---- - -Show an example + * This is called *__tight coupling__* -Dependency injection in ASP.NET: - -public class HomeController : Controller +### The solution -{ - -private readonly IUserRepository \_userRepository; +* What if, instead of directly creating the objects, they were provided by some interface that takes care of the creation? +* This way, even if the base class changes, the consuming classes won't care because they only know about the provider +* This provider is called *__Container__*, and the functionality being injected is called *__Service__* +* In ASP.NET, this container system is built in -public HomeController(IUserRepository userRepository) +### Dependency injection in ASP.NET +```csharp +public class HomeController : Controller { + private readonly IUserRepository _userRepository; -\_userRepository = userRepository; - + public HomeController(IUserRepository userRepository) + { + _userRepository = userRepository; + } + // User repository including all users is now accessible in HomeController } +``` -// User repository including all users is now accessible in HomeController - -} - -# Design Patterns - -If the concepts of a singleton and dependency injection flew over your head, don't worry about it - -The important thing is to know they exist so that when they come up again in ASP.NET, you have already familiarized yourself with the terms and understanding the logic behind ASP.NET becomes less overwhelming +## Design Patterns -There are many more design patterns, see the material [here](https://www.c-sharpcorner.com/UploadFile/bd5be5/design-patterns-in-net/) +* If the concepts of a singleton and dependency injection flew over your head, don't worry about it -![](imgs/15%20Design%20Patterns%20in%20C%23_1.png) +* The important thing is to know they exist so that when they come up again in ASP.NET, you have already familiarized yourself with the terms + * Thus, understanding the logic behind ASP.NET becomes less overwhelming +* There are many more design patterns, see the material [here](https://www.c-sharpcorner.com/UploadFile/bd5be5/design-patterns-in-net/) + ```csharp + public void ConfigureServices(IServiceCollection services) + { + services.AddSingleton(); + services.AddControllersWithViews(); + } + ``` diff --git a/imgs/15 Design Patterns in C#_1.png b/imgs/15 Design Patterns in C#_1.png deleted file mode 100644 index b0d4567..0000000 Binary files a/imgs/15 Design Patterns in C#_1.png and /dev/null differ