![请添加图片描述](https://img-blog.csdnimg.cn/23cd89d604f646c885b27407f6dc184b.png)
1.抽象接口 Bike
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace decorator
{
interface Bike
{
string GetDescription();
int GetPrice();
}
}
2.被装饰者 BigBike
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace decorator
{
class BigBike : Bike
{
private string description = "大号自行车";
public string GetDescription()
{
return description;
}
public int GetPrice()
{
return 200;
}
}
}
3.装饰者 BikeDecorator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace decorator
{
class BikeDecorator : Bike
{
private string description = "这是个装饰器";
public virtual string GetDescription()
{
return description;
}
public virtual int GetPrice()
{
return 0;
}
}
}
4.防爆胎装饰器(具体装饰器)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace decorator
{
class RSCBikeDecorator : BikeDecorator
{
private string description = "增加一个防爆胎";
private Bike bike;
public RSCBikeDecorator(Bike bike)
{
this.bike = bike;
}
public override string GetDescription()
{
return this.bike.GetDescription() + "," + this.description;
}
public override int GetPrice()
{
return this.bike.GetPrice() + 100;
}
}
}
5.喇叭装饰器(具体装饰器)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace decorator
{
class SuonaBikeDecorator : BikeDecorator
{
private string description = "增加一个喇叭";
private Bike bike;
public SuonaBikeDecorator(Bike bike)
{
this.bike = bike;
}
public override string GetDescription()
{
return this.bike.GetDescription() + "," + this.description;
}
public override int GetPrice()
{
return this.bike.GetPrice() + 50;
}
}
}
6、测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace decorator
{
class Program
{
static void Main(string[] args)
{
Bike bigBike = new BigBike();
bigBike = new RSCBikeDecorator(bigBike);
bigBike = new SuonaBikeDecorator(bigBike);
bigBike = new SuonaBikeDecorator(bigBike);
Console.WriteLine(bigBike.GetDescription());
Console.WriteLine("价格:" + bigBike.GetPrice().ToString());
Console.ReadLine();
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/9f3e15b8f0e840a38aeebdd4c155d973.png)
7.装饰器优点
- 装饰模式比继承有更多的灵活性
- 可以使用不同的装饰器 排列组合,符合开闭原则。
8.装饰器缺点
- 增加了许多子类,过度使用使得程序很复杂。
- 增加系统的复杂度,加大学习理解的难度。