Design Patterns «Prev Next»

Lesson 7Pattern scope
ObjectiveDistinguish between Class and Object patterns and know when to use each.

Design Pattern Scope: Class vs. Object

In the GoF catalog, scope describes where the variability is resolved: Class patterns use inheritance and are decided largely at compile time; Object patterns use composition/delegation and are decided at run time. Both scopes appear across creational, structural, and behavioral categories.

At a glance

Common misconceptions (quick fixes)

Decision guide

Mini examples (Java)

Class scope - Template Method (compile-time skeleton, subclasses fill steps):

abstract class ReportGenerator {
  public final String generate() {            // algorithm skeleton
    String data = fetch();
    String normalized = transform(data);
    return render(normalized);
  }
  protected abstract String fetch();
  protected String transform(String d) { return d.trim(); } // default step
  protected abstract String render(String normalized);
}

final class HtmlReport extends ReportGenerator {
  protected String fetch() { return "..."; }
  protected String render(String s) { return "<html>" + s + "</html>"; }
}

Object scope - Strategy (runtime-composable policy):

interface Compression {
  byte[] apply(byte[] input);
}

final class GzipCompression implements Compression {
  public byte[] apply(byte[] input) { /* ... */ return input; }
}

final class ZipCompression implements Compression {
  public byte[] apply(byte[] input) { /* ... */ return input; }
}

final class BackupService {
  private Compression strategy;
  BackupService(Compression strategy) { this.strategy = strategy; }
  void setStrategy(Compression c) { this.strategy = c; } // swap at runtime
  byte[] backup(byte[] payload) { return strategy.apply(payload); }
}

GoF scope map (concise)

Representative, not exhaustive. When in doubt, prefer the object form.

Trade-offs by scope

Checklist


SEMrush Software 7 SEMrush Banner 7