Wednesday, December 17, 2014

Decorator Design Pattern - another example

Hi all

Another example of Decorator Design pattern implementation - create text decorator. For example, i create string. My goal - create architecture, which makes possible to change string on the fly - change register, remove spaces etc

My Unit Test shall looks like:

Component component = new LowerRegisterDecorator(new RemoveSpacesDecorator(new BaseString("MaMa PaPa")));
string text = component.Text();

Expected result: mamapapa

Lets coding
First of all, UML:

Code:

class BaseComponent.cs:

namespace TextDecorator
{
    public class BaseString : Component
    {
        private string _text;

        public BaseString(string text)
        {
            _text = text;
        }

        public override string Text()
        {
            return _text;
        }
    }
}

Class Component.cs:

using System;

namespace TextDecorator
{
    public abstract class Component
    {
        public abstract String Text();
    }
}

Class ComponentDecorator.cs:

namespace TextDecorator
{
    public abstract class ComponentDecorator : Component
    {
        protected Component _component;
        public ComponentDecorator(Component component)
        {
            _component = component;
        }
    }

    public class UpperRegisterDecorator : ComponentDecorator
    {
        public UpperRegisterDecorator(Component component) : base(component) { }

        public override string Text()
        {
            return _component.Text().ToUpper();
        }
    }

    public class LowerRegisterDecorator : ComponentDecorator
    {
        public LowerRegisterDecorator(Component component) : base(component) { }

        public override string Text()
        {
            return _component.Text().ToLower();
        }
    }
    
    public class RemoveSpacesDecorator : ComponentDecorator
    {
        public RemoveSpacesDecorator(Component component) : base(component) { }

        public override string Text()
        {
            return _component.Text().Replace(" ","");
        }
    }
}

No comments:

Post a Comment