一些例子。在这里,我假设您必须有销售税的注册费和服务税的销售税。
interface Payable {
public float getAmount();
}
abstract class PayableDecorator implements Payable {
private Payable base;
public PayableDecorator(Payable base) {
this.base = base;
}
public Payable getBase() {
return base;
}
}
class Fee implements Payable {
private float value;
public Fee(float value) {
this.value = value;
}
public float getAmount() {
return value;
}
}
class RegistrationFee extends PayableDecorator {
private float registrationPercentage;
public RegistrationFee(Payable fee, float pct) {
super(fee);
registrationPercentage = pct;
}
public float getRegistrationPercentage() {
return registrationPercentage();
}
public float getAmount() {
return getBase() * (1 + registrationPercentage);
}
}
class SaleTax extends PayableDecorator {
private float salePercentage;
public SaleTax(RegistrationFee registration, float pct) {
super(registration);
salePercentabe = pct;
}
public float getAmount() {
return getBase() * (1 + salePercentage);
}
}
class SericeTax extends PayableDecorator {
private float servicePercentage;
public SaleTax(SaleTax registration, float pct) {
super(registration);
salePercentabe = pct;
}
public float getAmount() {
return getBase() * (1 + servicePercentage);
}
}
使用:
Payable totalTax = new ServiceTax(new SaleTax(new RegistrationFee(new Fee(100), .1), .03), .01);