CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 5 of 7 · 2 min read

Combining patterns

Five patterns, one small design.

Real designs use several patterns together, each for its own job. Consider a system that texts a user when a room is booked.

  • The booking system announces "booked" to whoever cares. That is an Observer.
  • The text goes through a vendor's class that has the wrong method names. An Adapter makes it look like the system's own Channel interface.
  • Every send should be logged, without editing the sender. A Decorator adds that.
  • The message wording may vary by event or language. A Strategy renders it.
  • A factory picks and builds the channel by name.
interface Channel { void send(String to, String msg); }

class SmsChannel implements Channel {                // adapter over the vendor
    private final VendorSms v;
    SmsChannel(VendorSms v) { this.v = v; }
    public void send(String to, String msg) { v.push(to, msg); }
}

class LoggingChannel implements Channel {            // decorator
    private final Channel inner; private final List<String> log;
    LoggingChannel(Channel c, List<String> log) { inner = c; this.log = log; }
    public void send(String to, String msg) { log.add("send to " + to); inner.send(to, msg); }
}

interface Template { String render(String name); }  // strategy

class ChannelFactory {                               // simple factory
    static Channel create(String kind, VendorSms v, List<String> log) {
        if (kind.equals("SMS")) return new LoggingChannel(new SmsChannel(v), log);
        throw new IllegalArgumentException("unknown channel " + kind);
    }
}

Wiring them in main takes a few lines. The booking code publishes an event for user "asha". The subscriber renders the message with the template and sends it on the channel. The vendor receives "asha:Hi asha, your room is booked", and the log holds "send to asha".

Each pattern is small and answers one need. Remove any one and the others still work. A different channel is an adapter and a line in the factory. A different message is a lambda. The booking code never mentions the vendor.

Notice what was left out. No state machine, no composite, no singleton, because nothing in the requirement asked for them. In a round, say which patterns you used and also which you decided not to use. That shows judgement.

Check yourself: 1. Which pattern lets the booking code stay ignorant of who is listening? 2. What does the vendor receive for user "asha"? 3. Which patterns were left out, and why?