【发布时间】:2018-04-03 09:49:46
【问题描述】:
所以我创建了这样的东西:
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}";
}
}
我正在这样装饰学生:
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();
让我想知道的是,如果我将 ScienceStudentDecorator 更改为继承并持有 Student,它的工作原理完全相同。我还在装饰学生。我只是跳过与学生装饰者的仪式。我的问题是我误解了这个概念吗?
更改版本:
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}";
}
}
Student 和 ScienceDecorator 的创建完全一样。
【问题讨论】:
-
您似乎缺少的一点是装饰器模式适用于具有行为的服务。它最适用于做某事的服务,而不是您的
Student类,后者看起来更像一个数据传输对象 (DTO)。
标签: c# .net design-patterns decorator