using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 装饰
{
class Program
{
//办公桌
public class officeDesk
{
public officeDesk()
{ }
private string userName;
public officeDesk(string userName)
{
this.userName = userName;
}
public virtual void show()
{
Console.WriteLine("{0}的办公桌:",userName );
}
}
//装饰者
public class Decorator : officeDesk
{
//需要知道装饰对象,对应UML中的聚合
protected officeDesk desk;
//装扮办公桌
public void setDecortate(officeDesk desk)
{
this.desk = desk;
}
public override void show()
{
if (desk!=null)
{
desk.show();
}
}
}
//具体装饰类
//电脑
public class computer:Decorator
{
public override void show()
{
base.show();
Console.WriteLine("一台电脑 ");
}
}
//电话
public class telephone : Decorator
{
public override void show()
{
base.show();
Console.WriteLine("一部电话 ");
}
}
//文件夹
public class file : Decorator
{
public override void show()
{
base.show();
Console.WriteLine("一个文件夹 ");
}
}
//盆栽
public class plant : Decorator
{
public override void show()
{
base.show();
Console.WriteLine("一盆盆栽 ");
}
}
//签字笔
public class pen : Decorator
{
public override void show()
{
base.show();
Console.WriteLine("一支签字笔 ");
}
}
//公章
public class seal : Decorator
{
public override void show()
{
base.show();
Console.WriteLine("一个公章 ");
}
}
static void Main(string[] args)
{
officeDesk renZong = new officeDesk("任总");
computer computer = new computer();
telephone telephone = new telephone();
file file = new file();
plant plant = new plant();
pen pen = new pen();
seal seal = new seal();
computer.setDecortate(renZong);
telephone.setDecortate(computer);
file.setDecortate(telephone);
plant.setDecortate(file);
pen.setDecortate(plant );
seal.setDecortate(pen);
seal.show();
Console.WriteLine();
officeDesk xiaoLi = new officeDesk("小李");
computer.setDecortate(xiaoLi);
file.setDecortate(computer);
pen.setDecortate(file );
pen.show();
Console.Read();
}
}
}
装饰者是在不改变原内容的基础上,动态地增加新的行为;
适配器则主要用来填补两个接口之间的差异,将一个接口转化为另一个接口;策略是以切换运算法则的方式变换功能。
原文地址:http://blog.csdn.net/ry513705618/article/details/38474803