装饰着模式比较简单也比较实用当要扩展的时候只要传入要包装的对象就好了,比起扩展方法需要一个静态类和一个静态方法比较好用点也比较直观明白
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
namespace ConsoleApplication2
{
public interface Tank
{
void shot();
void run();
}
public class tank2A : Tank
{
public void shot()
{
Console.WriteLine("tank20 shot");
}
public void run()
{
Console.WriteLine("tank20 run");
}
}
public class tank3A : Tank
{
public void shot()
{
Console.WriteLine("tank30 shot");
}
public void run()
{
Console.WriteLine("tank30 run");
}
}
public abstract class Decorata:Tank
{
Tank tank;
public Decorata(Tank tank)
{
this.tank = tank;
}
public void shot()
{
tank.shot();
Console.WriteLine("shotA");
}
public void run()
{
tank.run();
Console.WriteLine("runA");
}
}
public class DecorataA : Decorata
{
Tank tank;
public DecorataA(Tank tank):base(tank)
{
this.tank = tank;
}
public void shot()
{
tank.shot();
Console.WriteLine("shotA");
}
public void run()
{
tank.run();
Console.WriteLine("runA");
}
}
public class DecorataB : DecorataA
{
Tank tank;
public DecorataB(Tank tank)
: base(tank)
{
this.tank = tank;
}
public void shot()
{
tank.shot();
Console.WriteLine("shotB");
}
public void run()
{
tank.run();
Console.WriteLine("runB");
}
}
public class Program
{
static void Main(string[] args)
{
Tank tank = new tank2A();
DecorataA da = new DecorataA(tank);
DecorataB db = new DecorataB(da);
db.shot();
db.run();
Console.ReadKey();
}
}
}