简体   繁体   中英

Using Decorator pattern with abstract class

Can I decorate abstract class Player by changing output of property Name. For example my class is :

public abstract class Player
{
    private FootBall ball;

    private string name;

    public Player(FootBall ball, string name)
    {
        this.name = name;
        this.ball = ball;
    }

    public string Name
    {
        get
        {
            return this.name;
        }
    }


    public virtual void Update()
    {
        Console.WriteLine(string.Format("Player {0} says that ball is at position {1} {2} {3}", this.Name, this.ball.Position.PositionX, this.ball.Position.PositionY, this.ball.Position.PositionZ));
    }

}

I have two classes GamePlayer and Referee both inheriting Player:

 GamePlayer : Player { // implementation }
 Referee: Player { // implementation }

I want to decorate property Name with for example two Decorations : SoccerPlayer and BasketBallPlayer. The property Name should return for example

John - basketballPlayer
John - soccerPlayer:
John - basketballPlayer - soccerPlayer

The decorator pattern works best with interfaces. If you wanted to use it with an abstract base class, you would need to make any methods you want to decorate virtual so that derived classes can override them to do their own processing before delegating to the decorated base types base.MyMethod method.

At this point you are basically using inheritance though. The only distinction between a decorated base class and inheritance is that in the decorator pattern, your derived class would have the Is A and Has A relationship to the base class, whereas inheritance would only have the Is A relationship. It would probably be indistinguishable from outside your derived class, so might as well just inherit.

https://msdn.microsoft.com/en-us/library/9fkccyh4.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM