C# / C# Design Patterns

Exploring Structural Patterns

This tutorial explores Structural Patterns in C#, focusing on the Adapter and Decorator patterns. You will learn how these patterns can help you to create flexible and efficient c…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers popular design patterns to build maintainable and scalable applications in C#.

1. Introduction

Goal of the Tutorial

This tutorial aims to introduce you to the concepts of Structural Patterns in C#, specifically focusing on the Adapter and Decorator patterns.

What You Will Learn

By the end of this tutorial, you will be able to:

  • Understand the concept of Structural Patterns
  • Implement the Adapter pattern in C#
  • Implement the Decorator pattern in C#

Prerequisites

Basic understanding of C# programming and Object-Oriented Programming (OOP) concepts is required.

2. Step-by-Step Guide

Structural Patterns

Structural Patterns in programming provide a manner to define relationships between classes or objects so that they can form larger structures. They simplify the structure and promote reusability.

Adapter Pattern

The Adapter pattern is a structural design pattern that allows objects with incompatible interfaces to work together. It wraps itself around an object and exposes a standard interface to interact with that object.

Here's an example of an Adapter pattern:

// the 'Adaptee'
public class OldSystem
{
    public string OldRequest()
    {
        return "Old System";
    }
}

// the 'Adapter'
public class Adapter : INewSystem
{
    private OldSystem _oldSystem;

    public Adapter(OldSystem oldSystem)
    {
        _oldSystem = oldSystem;
    }

    public string Request()
    {
        return $"Adapter: ({_oldSystem.OldRequest()})";
    }
}

// the 'Target'
public interface INewSystem
{
    string Request();
}

In the above example, Adapter is making the OldSystem compatible with INewSystem.

Decorator Pattern

The Decorator pattern provides a way to add new behavior to an object dynamically, without altering its implementation.

Here's an example of a Decorator pattern:

// 'Component'
public interface IComponent
{
    string Operation();
}

// 'ConcreteComponent'
public class Component : IComponent
{
    public string Operation()
    {
        return "ConcreteComponent";
    }
}

// 'Decorator'
public class Decorator : IComponent
{
    protected IComponent _component;

    public Decorator(IComponent component)
    {
        _component = component;
    }

    public virtual string Operation()
    {
        return _component.Operation();
    }
}

// 'ConcreteDecoratorA'
public class ConcreteDecoratorA : Decorator
{
    public ConcreteDecoratorA(IComponent comp) : base(comp) { }

    public override string Operation()
    {
        return $"ConcreteDecoratorA({base.Operation()})";
    }
}

In the above example, ConcreteDecoratorA is adding additional behavior to Component.

3. Code Examples

Adapter Pattern Example

class Program
{
    static void Main(string[] args)
    {
        OldSystem oldSystem = new OldSystem();
        INewSystem adapter = new Adapter(oldSystem);
        Console.WriteLine(adapter.Request());  // Output: Adapter: (Old System)
    }
}

Decorator Pattern Example

class Program
{
    static void Main(string[] args)
    {
        IComponent component = new Component();
        Console.WriteLine("Without decorator: ");
        Console.WriteLine(component.Operation());  // Output: ConcreteComponent

        Console.WriteLine("\nWith decorator: ");
        IComponent decorator = new ConcreteDecoratorA(component);
        Console.WriteLine(decorator.Operation());  // Output: ConcreteDecoratorA(ConcreteComponent)
    }
}

4. Summary

In this tutorial, we have learned about the Adapter and Decorator Structural Patterns. We also implemented these patterns in C#. Remember, the Adapter pattern is used to make two incompatible interfaces work together while the Decorator pattern allows adding new behavior to an object dynamically.

5. Practice Exercises

  1. Implement the Adapter pattern to make a Rectangle and Circle class work together.
  2. Implement the Decorator pattern to add a new 'draw' behavior to the Rectangle class.

Remember, the best way to learn is by doing. Try to modify and play with the code examples given above. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help