pad.mattdiesel.co.uk

Snippet - Decorator Example

Decorator Example (C#)


Created 2017-10-01 20:38:50.492340 by Matt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;

namespace decorator
{
    abstract class Sentence
    {
        public abstract string GetText();
    }

    class BasicSentence : Sentence
    {
        private string text;

        public BasicSentence(string s)
        {
            this.text = s;
        }
        public override string GetText()
        {
            return this.text;
        }
    }


    class CapitalisedSentence : Sentence
    {
        private Sentence sentence;

        public CapitalisedSentence(Sentence s) {
            sentence = s;
        }

        public override string GetText()
        {
            return sentence.GetText().ToUpper();
        }
    }

    class SubSentence : Sentence
    {
        private Sentence sentence;
        private int startIndex;
        private int length;

        public SubSentence(Sentence s, int start, int len)
        {
            sentence = s;
            startIndex = start;
            length = len;
        }

        public override string GetText()
        {
            return sentence.GetText().Substring(startIndex, length);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Sentence s1 = new BasicSentence("Hello, World!");

            Sentence s2 = new CapitalisedSentence(s1);

            Sentence s3 = new SubSentence(s2, 7, 5);

            Console.WriteLine(s1.GetText());
            Console.WriteLine(s2.GetText());
            Console.WriteLine(s3.GetText());
        }
    }
}