装饰模式学习
哈哈,今天重新看了一下设计模式中的装饰模式。发现每次看想的不一样,哈哈。
先传个图
代码随便写一个吧,超人的。突然觉得装饰模式不仅能有装饰作用,还有装饰的前后顺序。比如,超人的经典造型。内裤外穿。
我打算装饰出四种超人造型,只穿内裤,只穿外裤,内裤外穿,内裤内穿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DecoratorNameSpace
{
public abstract class Man
{
public abstract void Wear();
}
/// <summary>
/// 裸体超人
/// </summary>
public class SuperMan : Man
{
public override void Wear()
{
Console.WriteLine("裸体超人");
}
}
public abstract class Decorator : Man
{
public Man man;
public void SetComponent(Man man)
{
this.man = man;
}
public override void Wear()
{
man.Wear();
}
}
public class Decorator_穿外裤 : Decorator
{
public override void Wear()
{
base.Wear();
Console.WriteLine("超人穿上了外裤");
}
}
public class Decorator_穿内裤 : Decorator
{
public override void Wear()
{
base.Wear();
Console.WriteLine("超人穿上了内裤");
}
}
class Program
{
static void Main(string[] args)
{
//第一种情况:超人只穿内裤
SuperMan c1 = new SuperMan();
Decorator_穿内裤 db1 = new Decorator_穿内裤();
db1.SetComponent(c1);
db1.Wear();
Console.WriteLine("超人现在只穿了内裤");
Console.WriteLine("============================\n");
//第二种情况:超人只穿外裤
SuperMan c2 = new SuperMan();
Decorator_穿外裤 da2 = new Decorator_穿外裤();
da2.SetComponent(c2);
da2.Wear();
Console.WriteLine("超人现在只穿了外裤");
Console.WriteLine("============================\n");
//第三种情况:内裤穿在里面
SuperMan c3 = new SuperMan();
Decorator_穿内裤 db3 = new Decorator_穿内裤();
Decorator_穿外裤 da3 = new Decorator_穿外裤();
db3.SetComponent(c3);
da3.SetComponent(db3);
da3.Wear();
Console.WriteLine("超人现在内裤穿在了里面,外面穿了条裤子");
Console.WriteLine("============================\n");
//第四种情况:内裤穿在里面
SuperMan c4 = new SuperMan();
Decorator_穿外裤 da4 = new Decorator_穿外裤();
Decorator_穿内裤 db4 = new Decorator_穿内裤();
da4.SetComponent(c4);
db4.SetComponent(da4);
db4.Wear();
Console.WriteLine("超人经典造型,内裤外穿");
Console.WriteLine("============================\n");
}
}
}据说,.NET Framework和Java中流就是用的装饰模式。这个还没仔细看过,不过,他们好像都没有装饰的那个接口类了。有时间再研究了


浙公网安备 33010602011771号