Design Patterns in C#
1 of 3
Decorator Design Pattern in C#
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2021 March 25
The purpose of the Decorator Design Pattern is to extend a class
without changing the original class.
Example
class Program
{
interface ITestString
{
string GetString();
}
class TestString : ITestString
{
public string GetString()
{
return "ABC";
}
}
class DecoratedTestString : ITestString
{
private ITestString t;
private string s="";
public DecoratedTestString(ITestString t)
{
Design Patterns in C#
2 of 3
this.t = t;
}
public void Append(string s)
{
this.s += s;
}
public string GetString()
{
string s = t.GetString();
s += this.s;
return s;
}
}
static void Display(ITestString t)
{
Console.WriteLine(t.GetString());
}
static void Main(string[] args)
{
ITestString t = new TestString();
Display(t);
DecoratedTestString t1 = new DecoratedTestString(t);
t1.Append("XYZ");
Display(t1);
DecoratedTestString t2 = new DecoratedTestString(t1);
t2.Append("PQR");
Display(t2);
Design Patterns in C#
3 of 3
Console.ReadLine();
}
}
The output of the above code is given below.
ABC
ABCXYZ
ABCXYZPQR

Decorator Design Pattern in C#

  • 1.
    Design Patterns inC# 1 of 3 Decorator Design Pattern in C# Author: Kasun Ranga Wijeweera Email: krw19870829@gmail.com Date: 2021 March 25 The purpose of the Decorator Design Pattern is to extend a class without changing the original class. Example class Program { interface ITestString { string GetString(); } class TestString : ITestString { public string GetString() { return "ABC"; } } class DecoratedTestString : ITestString { private ITestString t; private string s=""; public DecoratedTestString(ITestString t) {
  • 2.
    Design Patterns inC# 2 of 3 this.t = t; } public void Append(string s) { this.s += s; } public string GetString() { string s = t.GetString(); s += this.s; return s; } } static void Display(ITestString t) { Console.WriteLine(t.GetString()); } static void Main(string[] args) { ITestString t = new TestString(); Display(t); DecoratedTestString t1 = new DecoratedTestString(t); t1.Append("XYZ"); Display(t1); DecoratedTestString t2 = new DecoratedTestString(t1); t2.Append("PQR"); Display(t2);
  • 3.
    Design Patterns inC# 3 of 3 Console.ReadLine(); } } The output of the above code is given below. ABC ABCXYZ ABCXYZPQR