Decorator Pattern – one more example

				
					

namespace decoratorpattern
{
    public interface ICake
    {
        void AddLayer(string layer);
        void ShowAllLayers();
    }

    public class StrawberryCake : ICake
    {
        private List<string> 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<string> 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);
            });
        }
    }
}

				
			
				
					

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);
        }
    }

}

				
			
				
					using decoratorpattern;

StrawberryCake cakeobj = new();
CakeDecorator decoratorObj = new CakeDecorator(cakeobj);
decoratorObj.Decorate("Happy Birthday Anurag");
cakeobj.ShowAllLayers();

				
			

This is strawberry cake

Happy Birthday Anurag

  1. ICakeDecorator :ICake
  2. In program.cs
    1. only decorator object is used now
    2. 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();

				
			

Leave a Comment