我正在尝试做Decorator Design Pattern,这就是我得到的:
我的基类是abstract Worker
类:
public abstract class Worker
{
public float Salary { get; set; }
public abstract float CountSalary();
}
Worker
是Driver
的基类:
public class Driver : Worker
{
public float Salary { get; set; }
public override float CountSalary() => Salary = 3000;
//for testing i just hard coded '3000' value
}
我的装饰器是abstract Bonus
类。它用奖金来装饰工人的工资。
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;
}
我在代码中以这种方式调用Decorator
:
Worker w = new AmountBonus(new Driver());
而不是3200
,而是新的Salary = 200
。您能告诉我,当我犯了一个错误而没有得到预期的Salary = 3200
时吗?为什么当我这样拨打电话:
Worker w = new AmountBonus(new AmountBonus(new Driver()));
我的Salary
不能累积到3400的值吗?
答案 0 :(得分:1)
我已经对您的代码进行了一些修改:
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();
}
然后您的代码的主要问题是CountSalary方法没有在任何地方调用,因此它不是必需的。第二个问题是Salary应该抽象,以便可以在子类中覆盖它。