Every time a function is extended, the interface may be permuted and combined, which will rapidly expand the subclass.
Decorate Model
Motivation:
Dynamic: Runtime
Static: Compile time
Intent:
Structure: [combined with examples]
Example
Abstract Tank
public abstract class Tank
{
public abstract void Shot();
public abstract void Run();
}
Specific Tank object: T51
public class Tank51 : Tank
{
public override void Shot()
{
}
public override void Run()
{
}
}
Decorator
public abstract class Decorator:Tank//接口继承
{
private Tanks _tank;//Has A 对象组合
public Decorator(Tanks _tank)//构造器
{
this._tank = _tank;
}
public override void Shot()
{
_tank.Shot();
}
public override void Run()
{
_tank.Run();
}
}
Specifically, DecoratorA and DecoratorB represent different functions of the extension
public class DecoratorA : Decorator
{
public DecoratorA(Tank _tank) : base(_tank)
{
}
public override void Shot()
{
//写功能扩展
//do shot..
base.Shot();
}
public override void Run()
{
//写功能扩展
//do run..
base.Run();
}
}
public class DecoratorB : Decorator
{
public DecoratorB(Tank _tank) : base(_tank)
{
}
public override void Shot()
{
//写功能扩展
//do shot..
base.Shot();
}
public override void Run()
{
//写功能扩展
//do run..
base.Run();
}
}
Specific use
class Use
{
public void Uses()
{
Tanks t51 = new Tank51();
DecoratorA da = new DecoratorA(t51);//添加一种扩展功能
DecoratorB db = new DecoratorB(da);//添加了A,B两种扩展功能
}
}
Key points.
The use of the decoration model in the .NET framework
shows the implementation of the interface
Example: In the two inherited interfaces, if some of the method signatures are consistent , it is necessary to use the display interface implementation to distinguish which interface the inherited method comes from.
public interface ICalLength
{
void Paint();
}
public interface ICalWeight
{
void Paint();
}
public class TV : ICalLength, ICalWeight
{
void ICalLength.Paint()
{
}
void ICalWeight.Paint()
{
}
}