装饰者模式
using System;
namespace Decorator
{
//抽象水果类
public abstract class Fruit
{
public abstract void Plant();
}
public class Apple : Fruit
{
//种植苹果树
public override void Plant()
{
Console.WriteLine("种植苹果树!");
}
}
//水果抽象装饰者
public abstract class FruitDecorator:Fruit
{
protected Fruit fruit;
public FruitDecorator(Fruit fruit)
{
this.fruit = fruit;
}
//种植水果
public override void Plant()
{
if (this.fruit != null)
{
this.fruit.Plant();
}
}
}
//为FruitDecorator类派生两个具体类
//松土装饰者
public class LoosenSoilDecorator : FruitDecorator
{
public LoosenSoilDecorator(Fruit fruit) : base(fruit) { }//这里base() 是调用FruitDecorator类的构造函数
public override void Plant()
{
base.Plant();
Loosen();
}
//为果树松土
private void Loosen() {
Console.WriteLine("为果树松土!");
}
}
//灌溉装饰者
public class ManureDecorator : FruitDecorator
{
public ManureDecorator(Fruit fruit) : base(fruit) { }//这里base() 是调用FruitDecorator类的构造函数
public override void Plant()
{
base.Plant();
Manure();
}
//为果树浇水
private void Manure()
{
Console.WriteLine("为果树浇水!");
}
}
class Program
{
static void Main(string[] args)
{
//创建苹果实例
Fruit myClass = new Apple();
//松土装饰者装饰苹果树
LoosenSoilDecorator Loosen = new LoosenSoilDecorator(myClass);
//灌溉装饰者装饰松土
ManureDecorator Manure = new ManureDecorator(Loosen);
Manure.Plant();
Console.ReadKey();
}
}
}
代码解析
本实例代码实现了装饰者模式,代码中首先创建了抽象水果类Fruit,然后由该类派生出具体苹果类Apple和抽象类FruitDecorator,该类的主要作用是通过其派生类对Fruit派生的具体类的Plant方法进行装饰。FruitDecorator类中保存了Fruit对象的引用,在FruitDecorator派生类的Plant方法中,首先调用Fruit对象的Plant方法,然后调用该方法的扩展方法,实现对Plant方法的扩展。在main函数中,首先创建了Apple的实例,然后利用LoosenSoilDecorator对象对Apple实例进行装饰,接着又利用ManureDecorator对象对LoosenSoilDecorator对象进行装饰。
在装饰者模式中满足了用组合代替继承的原则,以及开放封闭原则。实例代码中FruitDecorator类与Fruit类通过组合关系来扩展Plant方法,Fruit实现了对Plant方法扩展的开放和修改的封闭。
注意:
适配器模式与装饰者模式都是对类的功能进行修改,适配器模式实现了类方法接口形式的修改而不改变其功能,而装饰者模式的目的是改变类的方法的功能而不改变方法接口的形式。