- 装饰模式:装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
例子:
变形金刚:变形金刚在变形之前是一辆汽车,它可以在陆地上移动。当它变成机器人之后除了能够在陆地上移动之外,还可以说话;如果需要,它还可以变成飞机,除了在陆地上移动还可以在天空中飞翔。使用透明或者半透明装饰模式设计类图并编程实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 装饰模式
{
class Program
{
static void Main(string[] args)
{
Trans t = new Trans();
DecoratorPlan de = new DecoratorPlan(t);
de.Move();
Console.ReadKey();
}
}
abstract class car
{
public abstract void Move();
}
class Trans:car//变形金刚
{
public override void Move()
{
Console.WriteLine("在陆地上移动");
this.Tranfrom();
this.Speak();
}
void Speak()
{
Console.WriteLine("变形后,可以说话");
}
void Tranfrom()
{
Console.WriteLine("可以变形");
}
}
class Decorator:car
{
private car c;
public Decorator(car c)
{
this.c = c;
}
public override void Move()
{
c.Move();
}
}
class DecoratorPlan:Decorator
{
public DecoratorPlan(car c):base(c)
{
}
public override void Move()
{
base.Move();
this.tranPlane();
}
public void tranPlane()
{
Console.WriteLine("增加可以变成飞机,再天空飞翔");
}
}
}
如有错误之处还请指正!