Decorator

Intent
Add responsibilities to an object by wrapping it in others with the same interface, instead of creating a subclass for every combination.
Application
Physio, nutrition, open gym, a student discount… If every combination of extras is a class, the code explodes. Wrap the base plan in layers that add up and let Spring order them.
BasicWithPhysioMembershipControllerBasicWithNutritionAthleteBasicWithPhysioAndNutrition

The athlete sends physio + nutrition to the controller, which is wired to three plan classes; BasicWithPhysioAndNutrition is highlighted in red.

The three combination classes are highlighted: every new extra would double their number.

The Membership interface, PhysioAddOn, highlighted, and BasicMembership appear; PhysioAddOn sends monthlyFee() to the basic plan it wraps.

Nutrition asks Physio for the price, Physio asks the basic plan, and the answers come back: 59.00 from Basic to Physio and 84.00 from Physio to Nutrition. Both decorators are highlighted.

The Spring context appears. MembershipQuoter, highlighted together with the context, is wired to the decorator chain and to StudentDiscount.

physio + nutrition travels from the athlete to the controller, quote() to the quoter, and monthlyFee() goes down the chain: NutritionAddOn, PhysioAddOn, highlighted, and BasicMembership.

The quoter asks StudentDiscount, highlighted, for the price; it asks PhysioAddOn, and 84.00 comes back from Physio and 67.20 from the discount.

Inside the Spring context, BeanPostProcessor, highlighted, wraps the plan in AuditedMembership, also highlighted, which asks BasicMembership for the price.

Final view: the athlete, the controller, the quoter and the decorator chain, with StudentDiscount in front, all inside the Spring context.

Step 1 of 9

One class per combination

The box's basic plan costs €59 a month. On top of it, each athlete can add extras: physio (+€25) and nutrition (+€15).

The first version creates a subclass for every combination: BasicWithPhysio, BasicWithNutrition, BasicWithPhysioAndNutrition… An athlete asks for physio and nutrition, and the controller has to find the exact class for that combination.

Step 2 of 9

Then open gym arrives

With 2 extras you already have 4 classes. Add open gym (+€10) and it's 8. Add the student discount and it's 16. Every new extra doubles the classes.

And if physio gets more expensive, you have to find and change every class that includes it. Miss one and you charge the wrong price.

Step 3 of 9

An extra that wraps

The Decorator pattern swaps inheritance for wrappers:

  • Membership is the interface: description() and monthlyFee().
  • BasicMembership is the base plan.
  • PhysioAddOn is a Membership too, but it keeps another Membership inside (inner). Ask it for the price and it asks inner, then adds €25.

Physio doesn't know or care what's inside: a basic plan, another extra or ten of them.

Step 4 of 9

Layers that add up

For physio and nutrition you don't need a new class: you stack the layers.

new NutritionAddOn(new PhysioAddOn(new BasicMembership()))

When asked for the price, each layer asks the one inside and adds its own: basic gives €59.00, physio brings it to €84.00 and nutrition to €99.00. The description is built the same way: "Basic + Physio + Nutrition".

Step 5 of 9

Every extra, a bean

In Spring, each option is an AddOn bean: a name (physio, nutrition, open-gym, student) and how to wrap a plan. MembershipQuoter gets all of them in a List<AddOn>.

Look at each bean's @Order: Spring sorts the injected list by it. The extras go first (10, 20, 30) and the student discount, with @Order(DISCOUNTS), which is 1000, always last. The decorators themselves aren't beans: the quoter creates them on every quote, wrapping the plan with each requested option.

Step 6 of 9

A quote start to finish

An athlete asks for GET /api/memberships/quote?addOns=physio,nutrition:

  1. The quoter checks that both exist and aren't repeated. If not, the API answers 400.
  2. It starts from the basic plan and walks the AddOn list in order: wrap with physio, then with nutrition.
  3. It asks the outer layer for the price, which asks the one inside, which asks the basic plan.
  4. The API returns {"description": "Basic + Physio + Nutrition", "monthlyFee": "99.00"}.

Step 7 of 9

When order matters

Extras add up, so the stacking order doesn't matter. The student discount multiplies by 0.8, and there order does change the price:

  • Discount outside: (59 + 25) × 0.8 = €67.20.
  • Discount inside: 59 × 0.8 + 25 = €72.20, and physio is charged without the discount.

Thanks to @Order, the quoter always puts the discount as the outer layer, whether the client asks for student,physio or physio,student.

Step 8 of 9

Spring already does it for you

Spring has a hook for wrapping beans: a BeanPostProcessor sees every freshly created bean go by and can return another object instead. Return a decorator and that's what gets injected everywhere… as long as it's asked for by the Membership interface. Anyone asking for the concrete BasicMembership class won't find it anymore. That's how Spring builds the proxies from the Proxy lesson: the AOP auto-proxy creator is a BeanPostProcessor that returns a wrapper.

In the example, AuditEveryMembership wraps any Membership in an AuditedMembership that notes every time someone asks for the price.

Step 9 of 9

Recap

You started with one class per combination of extras and ended up with:

  • One base plan and one decorator per extra, all with the same interface.
  • Combinations on the fly, stacking layers that add their part.
  • AddOn beans with @Order, so the layers always come in the same order.
  • The discount outside, because it multiplies.

Cheatsheet →

Code

SubclassedPlans.java

public static class BasicWithNutrition extends Basic {
    @Override public Money monthlyFee() { return Money.eur("74.00"); }
}

public static class BasicWithPhysioAndNutrition extends Basic {
    // the price of each extra is copied here again, by hand: 59 + 25 + 15
    @Override public Money monthlyFee() { return Money.eur("99.00"); }
}

SubclassedPlans.java

public static class BasicWithNutrition extends Basic {
    @Override public Money monthlyFee() { return Money.eur("74.00"); }
}

public static class BasicWithPhysioAndNutrition extends Basic {
    // the price of each extra is copied here again, by hand: 59 + 25 + 15
    @Override public Money monthlyFee() { return Money.eur("99.00"); }
}

PhysioAddOn.java

public class PhysioAddOn extends MembershipDecorator {
    public PhysioAddOn(Membership inner) {
        super(inner);
    }

    @Override
    public String description() {
        return inner.description() + " + Physio";        // what's inside, plus my bit
    }

    @Override
    public Money monthlyFee() {
        return inner.monthlyFee().plus(Money.eur("25.00"));
    }
}

MembershipTest.java

Membership plan = new NutritionAddOn(new PhysioAddOn(new BasicMembership()));

assertThat(plan.description()).isEqualTo("Basic + Physio + Nutrition");
assertThat(plan.monthlyFee()).isEqualTo(Money.eur("99.00")); // 59 + 25 + 15

AddOns.java

@Bean @Order(DISCOUNTS)   // declared first on purpose: @Order, not position, puts it last
AddOn student() {
    return option("student", StudentDiscount::new);
}

@Bean @Order(10)
AddOn physio() {
    return option("physio", PhysioAddOn::new);
}

@Bean @Order(20)
AddOn nutrition() {
    return option("nutrition", NutritionAddOn::new);
}

@Bean @Order(30)
AddOn openGym() {
    return option("open-gym", OpenGymAddOn::new);
}

MembershipQuoter.java

public MembershipQuoter(Membership basic, List<AddOn> addOns) {
    this.basic = basic;
    this.addOns = addOns;              // every AddOn bean, sorted by @Order
}

public Membership quote(List<String> requested) {
    List<String> names = normalise(requested);
    Membership plan = basic;
    for (AddOn addOn : addOns) {
        if (names.contains(addOn.name())) {
            plan = addOn.wrap(plan);   // one more layer around the plan
        }
    }
    return plan;
}

MembershipTest.java

Membership discountLast = new StudentDiscount(new PhysioAddOn(new BasicMembership()));
Membership discountFirst = new PhysioAddOn(new StudentDiscount(new BasicMembership()));

assertThat(discountLast.monthlyFee()).isEqualTo(Money.eur("67.20"));  // (59 + 25) × 0.8
assertThat(discountFirst.monthlyFee()).isEqualTo(Money.eur("72.20")); // 59 × 0.8 + 25

SpringDoesItTooTest.java

static class AuditEveryMembership implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        // Spring offers every bean it creates: return a wrapper and that's what gets injected
        return bean instanceof Membership m ? new AuditedMembership(m) : bean;
    }
}

PhysioAddOn.java

public class PhysioAddOn extends MembershipDecorator {
    public PhysioAddOn(Membership inner) {
        super(inner);
    }

    @Override
    public String description() {
        return inner.description() + " + Physio";        // what's inside, plus my bit
    }

    @Override
    public Money monthlyFee() {
        return inner.monthlyFee().plus(Money.eur("25.00"));
    }
}

Quiz

1. With 4 extras that can be freely combined, how many classes do you need with one subclass per combination? And with decorators?

2. StudentDiscount takes 20% off whatever it wraps. Why must it be the outer layer?

3. What makes MembershipQuoter receive the AddOns in a specific order?

4. How does a Decorator differ from a Proxy?

Cheatsheet →

Run it