C# 用装饰模式实现蝌蚪变青蛙的过程
2010-09-30 22:45:13 来源:WEB开发网namespace DecoratorPattern
{
abstract class Animal
{
public abstract void Run();
}
}
namespace DecoratorPattern
{
class Tadpole :Animal
{
private Animal animal;
public Tadpole(Animal animal)
{
this.animal = animal;
}
public override void Run()
{
Console.WriteLine("我是一只蝌蚪");
}
}
}
namespace DecoratorPattern
{
class Frog:Animal
{
private Animal animal;
public Frog(Animal animal)
{
this.animal = animal;
}
public override void Run()
{
Console.WriteLine("我是一只青蛙");
}
}
}
然后游泳行为和呼吸行为也抽象为对象(在这里没有定义成接口)
namespace DecoratorPattern
{
class Swimable : Animal
{
private Animal animal;
public Swimable(Animal animal)
{
this.animal = animal;
}
public override void Run()
{
animal.Run();
Console.WriteLine("我是能游泳的");
}
}
}
namespace DecoratorPattern
{
class Breathable : Animal
{
private Animal animal;
public Breathable(Animal animal)
{
this.animal = animal;
}
public override void Run()
{
animal.Run();
Console.WriteLine("我上岸了,我能呼吸啦.");
}
}
}
上帝类型负责造物以及进化的过程
这样客户端看不出后台发生了什么变化,使用静态工厂模式隐藏创建和进化的过程。这样我们的客户端代码才会看起来优美流畅(哈哈顺便把我的代码也包括了)。
namespace DecoratorPattern
{
class God
{
public static Tadpole CreateKedou()
{
return new Tadpole(null);
}
internal static Swimable FirstJinhua(Animal single)
{
Swimable swimable = new Swimable(new Tadpole(single));
return swimable;
}
internal static Breathable SecondJinhua(Animal single)
{
Breathable breathable = new Breathable(new Frog(single));
return breathable;
}
}
}
具体的源码见附件:http://files.cnblogs.com/zengyongjoy/DecoratorPattern.rar
更多精彩
赞助商链接