dimanche 22 octobre 2017

Simplified decorator pattern. Is that correct?

So I've created something like this:

interface IStudent
{
    string DisplayInformation();
}

public class Student : IStudent
{
    public string Name { get; set; }

    public string Grade { get; set; }

    public int Age { get; set; }

    public virtual string DisplayInformation()
    {
        return $"{Name} - {Age} years old is in {Grade} grade";
    }
}

public class StudentDecorator : Student
{
    private Student _student;

    public StudentDecorator(Student student)
    {
        _student = student;
    }

    public override string DisplayInformation()
    {
        return _student.DisplayInformation();
    }
}

public class ScienceStudentDecorator : StudentDecorator
{
    public string Labs { get; set; }

    public ScienceStudentDecorator(Student student) : base(student)
    {
    }

    public override string DisplayInformation()
    {
        var info =  base.DisplayInformation();
        return $"{info}. Labse are {Labs}";
    }
}

And I am decorating the Student like that:

        var student = new Student
        {
            Age = 15,
            Grade = "Fourth",
            Name = "John"
        };

        var scienceStudent = new ScienceStudentDecorator(student)
        {
            Labs = "Biology, History, Physics"
        };

        Console.WriteLine(scienceStudent.DisplayInformation());

        Console.Read();

What makes me wonder is if I change the ScienceStudentDecorator to inherit and hold the Student it works exactly the same. I am still decorating the Student. I just skip the ceremony with Student Decorator. And my question is have I misunderstood the concept?

Changed version:

public class ScienceStudentDecorator : Student
{
    private Student _student;

    public string Labs { get; set; }

    public ScienceStudentDecorator(Student student)
    {
        _student = student;
    }

    public override string DisplayInformation()
    {
        var info =  _student.DisplayInformation();
        return $"{info}. Labse are {Labs}";
    }
}

The creation of both Student and ScienceDecorator is exactly the same.

Aucun commentaire:

Enregistrer un commentaire