Reader small image

You're reading from  Architecting ASP.NET Core Applications - Third Edition

Product typeBook
Published inMar 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123385
Edition3rd Edition
Languages
Right arrow
Author (1)
Carl-Hugo Marcotte
Carl-Hugo Marcotte
author image
Carl-Hugo Marcotte

Carl-Hugo Marcotte is a software craftsman who has developed digital products professionally since 2005, while his coding journey started around 1989 for fun. He has a bachelor's degree in computer science. He has acquired a solid background in software architecture and expertise in ASP.NET Core through creating a wide range of web and cloud applications, from custom e-commerce websites to enterprise applications. He served many customers as an independent consultant, taught programming, and is now a Principal Architect at Export Development Canada. Passionate about C#, ASP.NET Core, AI, automation, and Cloud computing, he fosters collaboration and the open-source ethos, sharing his expertise with the tech community.
Read more about Carl-Hugo Marcotte

Right arrow

Strategy, Abstract Factory, and Singleton Design Patterns

This chapter explores object creation using a few classic, simple, and yet powerful design patterns from the Gang of Four (GoF). These patterns allow developers to encapsulate and reuse behaviors, centralize object creation, add flexibility to our designs, or control object lifetime. Moreover, you will most likely use some of them directly or indirectly in all the software you build.

The GoF is the name given to Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, authors of Design Patterns: Elements of Reusable Object-Oriented Software (1994). In that book, they introduced 23 design patterns, some of which we revisit in this book.

Why are they that important? Because they are the building blocks of robust object composition and help create flexibility and reliability. I grouped these patterns in this chapter because they are the building blocks of Chapter 8, Dependency Injection, where we will...

The Strategy design pattern

The Strategy pattern is a behavioral design pattern that allows us to change object behaviors at runtime.

We can also use this pattern to compose complex object trees and rely on it to follow the Open/Closed Principle (OCP) without much effort. Moreover, it plays a significant role in the composition over inheritance way of thinking and is the backbone of dependency injection.

In this chapter, we focus on the behavioral part of the Strategy pattern. The next chapter covers how to use this pattern to compose systems dynamically.

Goal

The Strategy pattern aims to extract an algorithm (a strategy) from the host class that needs it (the context or consumer). That allows the consumer to decide on the strategy (algorithm) to use at runtime.

Design

Before any further explanation, let’s take a look at the following class diagram:

Figure 7.1: Strategy pattern class diagram

Based on the preceding diagram, the building...

The Abstract Factory design pattern

The Abstract Factory design pattern is a creational design pattern from the GoF. We use creational patterns to create other objects, and factories are a very popular way of doing that.

We use factories to create complex objects that can’t be assembled automatically by a dependency injection library. There’ll be more on that in the next chapter.

Goal

The Abstract Factory pattern is used to abstract the creation of a family of objects. It usually implies the creation of multiple object types within that family. A family is a group of related or dependent objects (classes).

Let’s think about creating automotive vehicles. There are multiple vehicle types, and there are multiple models and makes for each type. We can use the Abstract Factory pattern to model this sort of scenario.

The Factory Method pattern also focuses on creating a single type of object instead of a family. We only cover Abstract Factory...

The Singleton design pattern

The Singleton design pattern allows you to create and reuse a single instance of a class. We could use a static class to achieve almost the same goal, but not everything is doable using static classes. For example, a static class can’t implement an interface. We can’t pass an instance of a static class as an argument because there is no instance. We can only use static classes directly, which leads to tight coupling every time.

The Singleton pattern in C# is an anti-pattern. As a rule of thumb, we should never use it and use dependency injection instead. .NET and C# offer the tools to implement similar functionalities without the drawbacks, hence the recommendation to not use this pattern. One such drawback is poor testability. That said, it is a classic design pattern worth learning to at least avoid implementing it. We explore a better alternative in the next chapter.

Here are a few reasons why we are covering this pattern:

...

Summary

In this chapter, we explored our first GoF design patterns. These patterns expose some of the essential basics of software engineering—not necessarily the patterns themselves but the concepts behind them:

  • The Strategy pattern is a behavioral pattern that we use to compose most of our future classes. It allows you to swap behavior at runtime by composing an object with small pieces and coding against interfaces, following the SOLID principles.
  • The Abstract Factory pattern introduces the idea of abstracting away object creation, leading to a better separation of concerns. More specifically, it aims to abstract the creation of object families and follow the SOLID principles.
  • Even if we defined it as an anti-pattern, the Singleton pattern brings application-level objects to the table. It allows you to create a single instance of an object that lives for the whole lifetime of a program. The pattern violates most SOLID principles.

We also peeked...

Questions

Let’s take a look at a few practice questions:

  1. Why is the Strategy pattern a behavioral pattern?
  2. What is the goal of creational patterns?
  3. If I write the code public MyType MyProp => new MyType(); and I call the property twice (var v1 = MyProp; var v2 = MyProp;), are v1 and v2 the same instance or two different instances?
  4. Is it true that the Abstract Factory pattern allows us to add new families of elements without modifying the existing consuming code?
  5. Why is the Singleton pattern an anti-pattern?

Answers

  1. It helps manage behaviors at runtime, such as changing an algorithm in the middle of a running program.
  2. Creational patterns are responsible for creating objects.
  3. v1 and v2 are two different instances. The code on the right-hand side of the arrow operator is executed every time you call the property’s getter.
  4. Yes, it is true. That’s the primary goal of the pattern, as we demonstrated in the MidRangeVehicleFactory code sample.
  5. The Singleton pattern violates the SOLID principles and encourages the use of global (static) state objects. We can avoid this pattern most of the time.

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/ArchitectingASPNETCoreApps3e

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Architecting ASP.NET Core Applications - Third Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781805123385
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Carl-Hugo Marcotte

Carl-Hugo Marcotte is a software craftsman who has developed digital products professionally since 2005, while his coding journey started around 1989 for fun. He has a bachelor's degree in computer science. He has acquired a solid background in software architecture and expertise in ASP.NET Core through creating a wide range of web and cloud applications, from custom e-commerce websites to enterprise applications. He served many customers as an independent consultant, taught programming, and is now a Principal Architect at Export Development Canada. Passionate about C#, ASP.NET Core, AI, automation, and Cloud computing, he fosters collaboration and the open-source ethos, sharing his expertise with the tech community.
Read more about Carl-Hugo Marcotte