Im dealing with Decorator design pattern. What i got now:
My Base abstract class Worker
:
public abstract class Worker
{
public float UsdPerHour { get; set; }
public int HoursPerDay { get; set; }
public int DaysOfWork { get; set; }
public abstract float CountSalary();
}
Its abstract, because its base for my Workers
classes. i think its not necesery, what is inside that classes. If you want to, i will add it to my edit.
Next i start implementing my decorator. Each Worker
have CountSalary()
. I want to applying bonuses to their salary based on decorator.
We are starting on abstract Bonus
class:
public abstract class Bonus : Worker
{
public Bonus(Worker worker) => this.worker = worker;
public override float CountSalary() => worker.CountSalary();
private Worker worker { get; set; }
}
Bonus are base clas for AmountBonus
class.
public class AmountBonus : Bonus
{
public AmountBonus(Worker worker) : base(worker: worker){ }
// is this 'base' call correct?
public override float CountSalary()
{
throw new NotImplementedException();
}
private Worker worker;
}
My question is, how to get reference to object Worker worker
in base class (Bonus
) in concrete decorator class as AmountBonus
?
EDIT
Based on your help, can i delete private Worker worker
from AmountBonus
class, and play with worker
from base Bonus
class like base.worker
? Is it possible?
VS didnt tells me, that is not allowed
public override float CountSalary() => base.worker.CountSalary();
By turning your private Worker worker { get; set; }
into protected Worker worker { get; set; }
classes outside cannot access it, but base classes can. This works even if the base class is abstract
Edit: This would also be a good time to learn about C# naming conventions ;) MSDN docs
Edit 2: As this comment points out, you probably want to use a private set
with your Worker worker
Edit after question Edit: You still (only if you want) need the Worker in the Bonus
class but you do not need to declare private Worker worker;
again, as this (correctly pointed out by intellisense) hides the Bonus.worker
worker. If the Bonus.Worker
is set to protected, and not private, you can use it from your inherited classes without having to declare it again. This would be the result:
public abstract class Worker
{
public float UsdPerHour { get; set; }
public int HoursPerDay { get; set; }
public int DaysOfWork { get; set; }
public abstract float CountSalary();
}
public abstract class Bonus : Worker
{
public Bonus(Worker worker) => this.worker = worker;
public override float CountSalary() => worker.CountSalary();
protected Worker worker { get; private set; }
}
public class AmountBonus : Bonus
{
public AmountBonus(Worker worker) : base(worker: worker){ }
public override float CountSalary()
{
throw new NotImplementedException();
}
}