装饰器模式(C#)
先举个例子:
我们创建一个Person对象,
然后对他进行装饰:
1.装饰上红色的帽子
2.装饰上黑色的外套
那么我们这样写代码(部分代码)看上去会比较舒服
static void Main(string[] args)
{
//原本的张三
Console.WriteLine("********原本的张三*********");
IPerson person = new Person("张三", 18);
person.Introduct();
//装饰上红帽子
Console.WriteLine("*********装饰上红帽子************");
person = new PersonRedHatDecorator(person);
person.Introduct();
//装饰上黑外套
Console.WriteLine("*********装饰上黑外套************");
person = new PersonBlackJacketDecorator(person);
person.Introduct();
}
运行结果
这里就用到了装饰器模式
装饰器模式可以给现有的类添加一些装饰(额外的东西),但是又不改变原有的类
装饰器模式体现在PersonRedHatDecorator类的Introduct方法上,该方法实现上其实就是调用了传入的IPerson的方法,在此基础上有增加了别的操作,这样就起到了装饰的效果
重点观察PersonRedHatDecorator类:
class PersonRedHatDecorator : IPerson
{
private IPerson _person;
public PersonRedHatDecorator(IPerson person)
{
_person = person;
}
public void Introduct()
{
_person.Introduct();
Console.WriteLine("我有一顶红色的帽子");
}
}
完整代码:
using System;
namespace CSharpTest2
{
internal interface IPerson
{
void Introduct();
}
class Person : IPerson
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void Introduct()
{
Console.WriteLine($"我叫{Name},今年{Age}岁");
}
}
class PersonRedHatDecorator : IPerson
{
private IPerson _person;
public PersonRedHatDecorator(IPerson person)
{
_person = person;
}
public void Introduct()
{
_person.Introduct();
Console.WriteLine("我有一顶红色的帽子");
}
}
class PersonBlackJacketDecorator : IPerson
{
private IPerson _person;
public PersonBlackJacketDecorator(IPerson person)
{
_person = person;
}
public void Introduct()
{
_person.Introduct();
Console.WriteLine("我有一件黑色的外套");
}
}
class Program
{
static void Main(string[] args)
{
//原本的张三
Console.WriteLine("********原本的张三*********");
IPerson person = new Person("张三", 18);
person.Introduct();
//装饰上红帽子
Console.WriteLine("*********装饰上红帽子************");
person = new PersonRedHatDecorator(person);
person.Introduct();
//装饰上黑外套
Console.WriteLine("*********装饰上黑外套************");
person = new PersonBlackJacketDecorator(person);
person.Introduct();
}
}
}