CAKE TYPES
namespace decoratorpattern
{
public interface ICake
{
void AddLayer(string layer);
void ShowAllLayers();
}
public class StrawberryCake : ICake
{
private List layers = new ();
public void AddLayer(string layer)
{
layers.Add (layer);
}
public void ShowAllLayers()
{
Console.WriteLine("This is Strawberry Cake");
layers.ForEach(layer =>
{
Console.WriteLine(layer);
});
}
}
public class BlackForestCake : ICake
{
private List layers = new();
public void AddLayer(string layer)
{
layers.Add(layer);
}
public void ShowAllLayers()
{
layers.ForEach(layer =>
{
Console.WriteLine("This is BlackForestCake Cake");
Console.WriteLine($"layer -->", layer);
});
}
}
}
DECORATOR PATTERN
namespace decoratorpattern
{
public interface ICakeDecorator
{
void Decorate(string message);
}
public class CakeDecorator : ICakeDecorator
{
private readonly ICake _cake;
public CakeDecorator(ICake cake)
{
_cake = cake;
}
public void Decorate(string message)
{
_cake.AddLayer(message);
}
}
}
PROGRAM.CS
using decoratorpattern;
StrawberryCake cakeobj = new();
CakeDecorator decoratorObj = new CakeDecorator(cakeobj);
decoratorObj.Decorate("Happy Birthday Anurag");
cakeobj.ShowAllLayers();
OUTPUT
This is strawberry cake
Happy Birthday Anurag
GITHUB
https://github.com/AnuragDaCoder/decorator_before_refactor
Some refactoring done
- ICakeDecorator :ICake
REFACTORED CODE
- ICakeDecorator :ICake
- In program.cs
- only decorator object is used now
- It results in same output again
namespace decoratorpattern
{
public interface ICakeDecorator :ICake
{
void Decorate(string message);
}
public class CakeDecorator : ICakeDecorator
{
private readonly ICake _cake;
public CakeDecorator(ICake cake)
{
_cake = cake;
}
public void AddLayer(string layer)
{
_cake.AddLayer(layer);
}
public void Decorate(string message)
{
_cake.AddLayer(message);
}
public void ShowAllLayers()
{
_cake.ShowAllLayers();
}
}
}
using decoratorpattern;
StrawberryCake cakeobj = new();
CakeDecorator decoratorObj = new CakeDecorator(cakeobj);
decoratorObj.Decorate("Happy Birthday Anurag");
decoratorObj.ShowAllLayers();