Can a decorator in the Decorator Pattern be used to add additional methods?
I have a class, called Sprite:
public abstract class Sprite
{
protected Texture2D Image { get; set; }
protected Vector2 position;
public Sprite(Texture2D image, Vector2 position)
{
Image = image;
this.position = position;
}
public void Draw(SpriteBatch imageBatch)
{
spriteBatch.Draw(Image, position, Color.White);
}
}
Inheriting from it is AnimatedSprite:
public abstract class AnimatedSprite : Sprite
{
protected Point SheetSize { get; set; }
protected Point CurrentFrame { get; set; }
protected Point FrameSize { get; set; }
protected int MillisecondsPerFrame { get; set; }
protected int TimeSinceLastFrame { get; set; }
public AnimatedSprite(Point sheetSize, Point currentFrame, Point frameSize,
int millisecondsPerFrame, int timeSinceLastFrame, Texture2D image, Vector2 position)
: base(image, position)
{
SheetSize = sheetSize;
CurrentFrame = currentFrame;
FrameSize = frameSize;
MillisecondsPerFrame = millisecondsPerFrame;
TimeSinceLastFrame = timeSinceLastFrame;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Image,开发者_JAVA技巧 position,
new Rectangle(CurrentFrame.X * FrameSize.X,
CurrentFrame.Y * FrameSize.Y,
FrameSize.X, FrameSize.Y), Color.White);
}
}
Inhereting from that is Invader:
public class Invader : AnimatedSprite
{
public Invader(Point sheetSize, Point currentFrame, Point frameSize,
int millisecondsPerFrame, int timeSinceLastFrame, Texture2D image, Vector2 position)
: base(sheetSize, currentFrame, frameSize, millisecondsPerFrame, timeSinceLastFrame,
image, position)
{
}
}
I think this would be a good one to implement the decorator pattern. The problem is that in most examples of the decorator pattern I see a method from the root abstract class being inherited by the decorater, and no additional things, which I do have.
Can I use the decorator pattern here, and can I add additional stuff to the abstract AnimatedSprite class?
Decorators decorate objects that implement the Component interface. In that sense, your subclasses don't decorate 'root' objects; they don't aggregate the interface, but inherit it (Invader < AnimatedSprite < Sprite ).
So the pattern matching this scenario is not Decorator. It's basic Specialization as far as I can tell...
Things are not being added because the user of the Component interface sees no more than the interface. You can only partly change the implementation of the decorated Component.
Could you use decorator? I guess you could, to add a 'glow', for instance:
public class GlowingSprite : Sprite {
private Sprite sprite;
public override void Draw( SpriteBatch imageBatch ) {
sprite.Draw(imageBatch);
// decoration happens vvv
imageBatch.Overlay( GlowingOval, sprite.position ); //
}
}
精彩评论