Patternadvanced
Extension object
Also called extension object pattern, extensible object, extension interface, adaptable object.
The Extension object pattern adds interfaces to an object without changing its class. A client asks the object for an extension by its type, and it gets the extension or nothing.
- Family
- structural-design
- Intent
- Let an object get new interfaces after its class is published: put each new interface in a separate extension object, and let clients ask the object for an extension at run time.
- Also called
- Extensible object, Adaptable
Intent
Extension object is a structural pattern that lets an object take new interfaces without a change to its class. Each new interface is in a separate extension object. A client asks the object for an extension at run time and uses it if it is there.12
Problem
When a published interface gets a new method, all of its clients break. Erich Gamma gives the rule that a published interface is immutable, so a new method must go in a separate interface. Eclipse has such extension interfaces, for example IWorkbenchPart2, which adds methods to IWorkbenchPart. The cost is that a caller must find out at run time whether an object implements the extension interface.2
The same problem comes when different clients need different services from one object. If every service goes into the class of the object, the class gets large, and each client depends on services that it does not use.
Solution
The subject keeps its own small interface and one more operation: get the extension of a given type. The operation returns the extension object, or nothing if the subject has no such extension.
Client
| getExtension(WordCount)
v
Subject -------- extensions --------+-----------------+
getExtension(type) | |
WordCount Upper
(extension) (extension)
holds the subject holds the subject
The pattern has many forms in real systems:
- In Eclipse, an object that implements
IAdaptablehas the methodgetAdapter(Class<T> adapter). It returns an object of the given class, or null if it has no such adapter. Adaptable objects "can be dynamically extended to provide different interfaces".3 - In COM,
QueryInterfaceasks an object for a pointer to one of its interfaces, by an interface identifier. It returnsS_OKif the object supports the interface andE_NOINTERFACEif not.4 - In Windows Communication Foundation, an extensible object holds a collection of
IExtension<T>objects.Findreturns an extension of the given type, or null.5
Example
The example files show one program in each language. A Document holds text and a collection of extensions that is keyed by type. A WordCount extension counts the words. An Upper extension gives the text in capitals, and it is added only later. The client asks for Upper before and after the extension is added. The program prints:
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
class Document:
def __init__(self, text):
self.text = text
self._extensions = {}
def add_extension(self, extension):
self._extensions[type(extension)] = extension
def get_extension(self, kind):
return self._extensions.get(kind) # None if there is no such extension
class WordCount:
def __init__(self, doc):
self.doc = doc
def count(self):
return len(self.doc.text.split())
class Upper:
def __init__(self, doc):
self.doc = doc
def text(self):
return self.doc.text.upper()
def show_upper(doc):
upper = doc.get_extension(Upper)
print("upper: not supported" if upper is None else f"upper: {upper.text()}")
doc = Document("the quick brown fox")
doc.add_extension(WordCount(doc))
print(f"words: {doc.get_extension(WordCount).count()}")
show_upper(doc)
doc.add_extension(Upper(doc))
show_upper(doc)
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom. A dictionary keyed by class holds the extensions, and
getreturnsNonefor a missing one.
#include <cctype>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <typeindex>
#include <unordered_map>
struct Extension {
virtual ~Extension() = default;
};
class Document {
public:
explicit Document(std::string text) : text_(std::move(text)) {}
const std::string& text() const { return text_; }
template <typename T>
void add_extension() {
extensions_[std::type_index(typeid(T))] = std::make_unique<T>(*this);
}
template <typename T>
T* get_extension() const { // nullptr if there is no such extension
auto it = extensions_.find(std::type_index(typeid(T)));
return it == extensions_.end() ? nullptr : static_cast<T*>(it->second.get());
}
private:
std::string text_;
std::unordered_map<std::type_index, std::unique_ptr<Extension>> extensions_;
};
struct WordCount : Extension {
explicit WordCount(const Document& doc) : doc(doc) {}
int count() const {
std::istringstream in(doc.text());
std::string word;
int n = 0;
while (in >> word) ++n;
return n;
}
const Document& doc;
};
struct Upper : Extension {
explicit Upper(const Document& doc) : doc(doc) {}
std::string text() const {
std::string s = doc.text();
for (char& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
return s;
}
const Document& doc;
};
void show_upper(const Document& doc) {
if (auto* upper = doc.get_extension<Upper>()) {
std::cout << "upper: " << upper->text() << "\n";
} else {
std::cout << "upper: not supported\n";
}
}
int main() {
Document doc("the quick brown fox");
doc.add_extension<WordCount>();
std::cout << "words: " << doc.get_extension<WordCount>()->count() << "\n";
show_upper(doc);
doc.add_extension<Upper>();
show_upper(doc);
}
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom.
std::type_indexmakes a type usable as a map key. Thestatic_castis safe because each entry is stored under the type of its own object.
import java.util.HashMap;
import java.util.Map;
class Document {
final String text;
private final Map<Class<?>, Object> extensions = new HashMap<>();
Document(String text) { this.text = text; }
void addExtension(Object extension) { extensions.put(extension.getClass(), extension); }
<T> T getExtension(Class<T> kind) {
return kind.cast(extensions.get(kind)); // null if there is no such extension
}
}
class WordCount {
private final Document doc;
WordCount(Document doc) { this.doc = doc; }
int count() { return doc.text.split("\\s+").length; }
}
class Upper {
private final Document doc;
Upper(Document doc) { this.doc = doc; }
String text() { return doc.text.toUpperCase(); }
}
public class Main {
static void showUpper(Document doc) {
Upper upper = doc.getExtension(Upper.class);
System.out.println(upper == null ? "upper: not supported" : "upper: " + upper.text());
}
public static void main(String[] args) {
Document doc = new Document("the quick brown fox");
doc.addExtension(new WordCount(doc));
System.out.println("words: " + doc.getExtension(WordCount.class).count());
showUpper(doc);
doc.addExtension(new Upper(doc));
showUpper(doc);
}
}
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom. The lookup takes a
Class<T>and returns aTor null, which is the signature ofgetAdapterin Eclipse'sIAdaptable.
using System;
using System.Collections.Generic;
class Document
{
public readonly string Text;
private readonly Dictionary<Type, object> extensions = new();
public Document(string text) { Text = text; }
public void AddExtension(object extension) => extensions[extension.GetType()] = extension;
public T? GetExtension<T>() where T : class =>
extensions.TryGetValue(typeof(T), out var e) ? (T)e : null;
}
class WordCount
{
private readonly Document doc;
public WordCount(Document doc) { this.doc = doc; }
public int Count() => doc.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
}
class Upper
{
private readonly Document doc;
public Upper(Document doc) { this.doc = doc; }
public string Text() => doc.Text.ToUpperInvariant();
}
class Program
{
static void ShowUpper(Document doc)
{
var upper = doc.GetExtension<Upper>();
Console.WriteLine(upper is null ? "upper: not supported" : $"upper: {upper.Text()}");
}
static void Main()
{
var doc = new Document("the quick brown fox");
doc.AddExtension(new WordCount(doc));
Console.WriteLine($"words: {doc.GetExtension<WordCount>()!.Count()}");
ShowUpper(doc);
doc.AddExtension(new Upper(doc));
ShowUpper(doc);
}
}
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom. A
Dictionary<Type, object>holds the extensions, and a generic method finds one by its type. WCF has the same form inIExtensibleObject<T>andIExtensionCollection<T>.
class Document {
#extensions = new Map(); // keyed by class
constructor(text) {
this.text = text;
}
addExtension(extension) {
this.#extensions.set(extension.constructor, extension);
}
getExtension(kind) {
return this.#extensions.get(kind) ?? null;
}
}
class WordCount {
constructor(doc) {
this.doc = doc;
}
count() {
return this.doc.text.split(/\s+/).length;
}
}
class Upper {
constructor(doc) {
this.doc = doc;
}
text() {
return this.doc.text.toUpperCase();
}
}
function showUpper(doc) {
const upper = doc.getExtension(Upper);
console.log(upper === null ? "upper: not supported" : `upper: ${upper.text()}`);
}
const doc = new Document("the quick brown fox");
doc.addExtension(new WordCount(doc));
console.log(`words: ${doc.getExtension(WordCount).count()}`);
showUpper(doc);
doc.addExtension(new Upper(doc));
showUpper(doc);
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom. A
Mapcan use a class as its key, so the lookup is by type.
type Kind<T> = new (doc: Document) => T;
class Document {
text: string;
#extensions = new Map<Function, object>();
constructor(text: string) {
this.text = text;
}
addExtension(extension: object): void {
this.#extensions.set(extension.constructor, extension);
}
getExtension<T>(kind: Kind<T>): T | null {
return (this.#extensions.get(kind) as T | undefined) ?? null;
}
}
class WordCount {
doc: Document;
constructor(doc: Document) {
this.doc = doc;
}
count(): number {
return this.doc.text.split(/\s+/).length;
}
}
class Upper {
doc: Document;
constructor(doc: Document) {
this.doc = doc;
}
text(): string {
return this.doc.text.toUpperCase();
}
}
function showUpper(doc: Document): void {
const upper = doc.getExtension(Upper); // type: Upper | null
console.log(upper === null ? "upper: not supported" : `upper: ${upper.text()}`);
}
const doc = new Document("the quick brown fox");
doc.addExtension(new WordCount(doc));
console.log(`words: ${doc.getExtension(WordCount)?.count()}`);
showUpper(doc);
doc.addExtension(new Upper(doc));
showUpper(doc);
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom. A generic
getExtension<T>takes the class and returnsT | null, so the compiler makes the client handle a missing extension.
package main
import (
"fmt"
"strings"
)
type Document struct {
Text string
extensions []any
}
func (d *Document) AddExtension(e any) { d.extensions = append(d.extensions, e) }
// Extension returns the first extension of type T, and false if there is none.
func Extension[T any](d *Document) (T, bool) {
for _, e := range d.extensions {
if t, ok := e.(T); ok {
return t, true
}
}
var zero T
return zero, false
}
type WordCount struct{ doc *Document }
func (w *WordCount) Count() int { return len(strings.Fields(w.doc.Text)) }
type Upper struct{ doc *Document }
func (u *Upper) Text() string { return strings.ToUpper(u.doc.Text) }
func showUpper(d *Document) {
if u, ok := Extension[*Upper](d); ok {
fmt.Println("upper:", u.Text())
} else {
fmt.Println("upper: not supported")
}
}
func main() {
doc := &Document{Text: "the quick brown fox"}
doc.AddExtension(&WordCount{doc})
w, _ := Extension[*WordCount](doc)
fmt.Println("words:", w.Count())
showUpper(doc)
doc.AddExtension(&Upper{doc})
showUpper(doc)
}
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom. A type assertion
e.(T)checks the type of each extension, and the comma-ok form reports a missing one.Tcan also be an interface type, so a client can ask for a behaviour instead of a concrete type.
use std::any::{Any, TypeId};
use std::collections::HashMap;
struct Document {
text: String,
extensions: HashMap<TypeId, Box<dyn Any>>,
}
impl Document {
fn new(text: &str) -> Document {
Document { text: text.to_string(), extensions: HashMap::new() }
}
fn add_extension<T: Any>(&mut self, extension: T) {
self.extensions.insert(TypeId::of::<T>(), Box::new(extension));
}
fn get_extension<T: Any>(&self) -> Option<&T> {
self.extensions.get(&TypeId::of::<T>())?.downcast_ref::<T>()
}
}
// The extensions take the document as an argument, so that they do not
// hold a reference to the object that owns them.
struct WordCount;
impl WordCount {
fn count(&self, doc: &Document) -> usize {
doc.text.split_whitespace().count()
}
}
struct Upper;
impl Upper {
fn text(&self, doc: &Document) -> String {
doc.text.to_uppercase()
}
}
fn show_upper(doc: &Document) {
match doc.get_extension::<Upper>() {
Some(upper) => println!("upper: {}", upper.text(doc)),
None => println!("upper: not supported"),
}
}
fn main() {
let mut doc = Document::new("the quick brown fox");
doc.add_extension(WordCount);
let words = doc.get_extension::<WordCount>().map(|w| w.count(&doc));
println!("words: {}", words.unwrap_or(0));
show_upper(&doc);
doc.add_extension(Upper);
show_upper(&doc);
}
words: 4
upper: not supported
upper: THE QUICK BROWN FOX
- Verdict: idiom.
TypeIdis the key, anddowncast_refondyn Anygives back the typed extension as anOption. An extension that held a reference to its owner would need shared ownership, so here the owner is passed to each method.
Consequences
The benefits:
- New interfaces come without a change to the published interface of the subject, so the clients of the subject do not break.2
- Each client sees only the extensions that it asks for.
- Extensions can be added at run time. An Eclipse adaptable object can get new adapters from adapter factories.3
The costs:
- A run-time check. The caller must find out at run time whether the subject has the extension, and it must handle the case where it does not.
getAdaptercan return null, andQueryInterfacecan returnE_NOINTERFACE.234 - Rules for the lookup. COM requires that the set of interfaces of an object is static, and that
QueryInterfaceis reflexive, symmetric and transitive.4 A homemade lookup has no such rules unless the design gives them. - Ambiguity. If several extensions in a WCF collection have the same type,
Findreturns one of them.5
The key of the lookup matters. Here the extensions are keyed by name, and the client asks with a spelling that is a little different. The lookup does not fail with an error. It returns nothing, and the client reports that the document has no word count:
This code runs but gives a wrong answer on purpose.
class Document:
def __init__(self, text):
self.text = text
self._extensions = {}
def add_extension(self, name, extension):
self._extensions[name] = extension
def get_extension(self, name):
return self._extensions.get(name)
class WordCount:
def __init__(self, doc):
self.doc = doc
def count(self):
return len(self.doc.text.split())
doc = Document("the quick brown fox")
doc.add_extension("word_count", WordCount(doc))
counter = doc.get_extension("wordcount")
print("words: not supported" if counter is None else f"words: {counter.count()}")
words: not supported
Eclipse and WCF key the lookup by type, as in getAdapter(Class<T> adapter) and in the Find method of IExtensionCollection<T>.35 A misspelled class name is then an error at the call, not a silent miss:
class Document:
def __init__(self, text):
self.text = text
self._extensions = {}
def add_extension(self, extension):
self._extensions[type(extension)] = extension
def get_extension(self, kind):
return self._extensions.get(kind)
class WordCount:
def __init__(self, doc):
self.doc = doc
def count(self):
return len(self.doc.text.split())
doc = Document("the quick brown fox")
doc.add_extension(WordCount(doc))
counter = doc.get_extension(WordCount)
print("words: not supported" if counter is None else f"words: {counter.count()}")
try:
doc.get_extension(WordCounter)
except NameError as e:
print(f"error: {e}")
words: 4
error: name 'WordCounter' is not defined
When not to use it
- The set of interfaces is known and small. The class can implement them directly, and clients need no run-time check.
- The interface is not published, so its clients can change with it.
- The language can add methods to an existing interface without breaking clients. Gamma notes that in Java, an abstract class can get a new method with a default implementation, and all clients continue to work.2
Variants and related patterns
Adapter factories. In Eclipse, adapters are created by adapter factories, which adapter managers keep by type. The subject does not need to store its extensions, and PlatformObject gives a default getAdapter that asks the adapter manager.36
Type-based dictionary. WCF uses the extensions collection of an object as a dictionary keyed by type, so that one component can store state on an object and another component can find it.5
Adapter. An extension that gives a subject a new interface is an Adapter pattern that the subject itself hands out. Eclipse calls its extensions adapters.3
Marker interface. A Marker interface is a type check with no methods. An extension lookup is a type check that also returns an object with methods.
Known uses
- Eclipse: PlatformObject.java at R4_38 declares
public abstract class PlatformObject implements IAdaptable, and itsgetAdapterreturnsAdapterManager.getDefault().getAdapter(this, adapter).6 Gamma namedIAdaptableas an example of the Extension Object pattern.2 - COM: a client calls
QueryInterfaceon a COM object to get a pointer to another of its interfaces, by the interface identifier.4 - Windows Communication Foundation:
ServiceHostBase,InstanceContext,OperationContextandIContextChannelare extensible objects.5
References
- Robert C. Martin, Dirk Riehle and Frank Buschmann (eds.), Pattern Languages of Program Design 3, Addison-Wesley, Part 1, chapter 6: Extension Object, by Erich Gamma
- Bill Venners, Design Principles from Design Patterns: A Conversation with Erich Gamma, Part III, Artima, June 6, 2005, section on API evolution; footnote 4
- Interface IAdaptable, Eclipse Platform API Specification, interface description; getAdapter
- IUnknown::QueryInterface(REFIID,void**) method (unknwn.h), Microsoft Learn, description; Return value; Remarks
- Extensible objects, Windows Communication Foundation, Microsoft Learn, The IExtensibleObject<T> Pattern; Extensible Objects in Windows Communication Foundation
- Eclipse Equinox R4_38 source, org/eclipse/core/runtime/PlatformObject.java, PlatformObject and getAdapter, lines 47 to 74
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 8N285T Edit this page History Report an error Markdown