简体   繁体   中英

Decorator with abstraction, dont get decorated value properly

Im trying to do Decorator Design Pattern and it is what i got:

My base class is an abstract Worker class:

public abstract class Worker
{
    public float Salary { get; set; }
    public abstract float CountSalary();
}

Worker is a base class for Driver :

public class Driver : Worker
{
    public float Salary { get; set; }
    public override float CountSalary() => Salary = 3000;
    //for testing i just hard coded '3000' value
}

My Decorator is an abstract Bonus class. It decorating worker's salary with bonuses.

public abstract class Bonus : Worker
{
    public Bonus(Worker worker) => this.worker = worker;
    public override float CountSalary() => worker.Salary;
    protected Worker worker { get; private set; }
}

public class AmountBonus : Bonus
{
    public AmountBonus(Worker worker) : base(worker: worker){ }
    public override float CountSalary() => base.worker.Salary + 200;
}

I make a call of a Decorator in this way in my code:

Worker w = new AmountBonus(new Driver());

And instead of 3200 , new Salary = 200 . Could you tell me, when i make a mistake and i dont get predicted Salary = 3200 ? Why when i make call like this:

Worker w = new AmountBonus(new AmountBonus(new Driver()));

My Salary dont stack to 3400 value?

I have made some modifications to your code :

 public abstract class Worker
{
    public abstract float Salary { get; } 
}

public class Driver : Worker
{
       public class Driver : Worker
      {
    float _salary = 0;
    public Driver(float Salary)
    {
        _salary = Salary;
    } 
    public override float Salary { get { return _salary; } } 
    //for testing i just hard coded '3000' value
   }

}

public abstract class Bonus : Worker
{
    public Bonus(Worker worker) => this.worker = worker; 
    protected Worker worker { get; private set; }
}

public class AmountBonus : Bonus
{
    public AmountBonus(Worker worker) : base(worker: worker) { }
    public override float Salary
    {
        get
        {
            return worker.Salary +200;
        }
    }

}


  static void Main(string[] args)
    {
        var driver = new Driver(3200);

        Console.WriteLine(driver.Salary);
        var driverSalWithBonus = new AmountBonus(driver);
        Console.WriteLine(driverSalWithBonus.Salary);
        Console.ReadLine();
    }

Then main problem with your code was CountSalary method was not called anywhere and its not required. The second problem was Salary should abstract so that it can be overwritten in the child classes.

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