首页 > 代码库 > 装饰模式(Decorator)

装饰模式(Decorator)

 

动态地给一个对象增加一些额外的职责。就增加功能而言,Decorator模式比生成子类更为灵活。

 

public class Tank

{

public abstract void Shot();

public abstract void Run();

}

public class T50 extends Tank

{

public override void Shot(){};

public override void Run(){};

}

public class T75 extends Tank

{

public override void Shot(){};

public override void Run(){};

}

public  abstract class Decorator extends Tank

{

private Tank tank;

public Decorator(Tank tank)

{

this.tank = tank;

}

void Shot()

{

tank.Shot();

}

void Run()

{

tank.Run();

}

}

public class DecoratorA extends Decorator 

{

public DecoratorA(Tank tank)

{

super(tank);

}

public override void Shot()

{

  红外

  base.shot();

}

public override void Run()

{

功能扩展 红外

base.Run();

}

}

public class DecoratorB extends Decorator 

{

public DecoratorB(Tank tank)

{

super(tank);

}

public override void Shot()

{

  功能扩展 两栖

  base.shot();

}

public override void Run()

{

功能扩展 两栖

base.Run();

}

}

class App

{

public static void Main()

{

Tank tank = new T50();

DecoratorA da = new Decorator(tank);红外功能

DecoratorB db = new Decorator(da); 红外,两栖

}

}