Programming Search⌘K

Patternadvanced

Type Object

Also called type object pattern, TypeObject.

A type object is an instance that represents a kind of object. Each typed object refers to its type object, so new kinds are new data, not new classes.

Family
behavioral-design
Intent
Allow the flexible creation of new classes by creating a single class, each instance of which represents a different type of object.

Intent

Type Object allows the flexible creation of new "classes" by creating a single class, each instance of which represents a different type of object.1

Problem

A program often has many kinds of a thing, and each kind has its own data. In Nystrom's example, a game has monsters of different breeds, such as dragons and trolls. The breed determines the starting health of a monster and its attack string.1

The obvious design makes each breed a subclass of Monster. Then each new breed needs new code, and the kinds are fixed in the type system of the language. This is too rigid in these cases:1

  • You do not know which types you will need up front. For example, a game can download content with new breeds of monsters.
  • You want to modify or add types without a change to the code or a new compilation.

Solution

Define a type object class and a typed object class. Each instance of the type object class represents a different logical type. Each typed object stores a reference to the type object that describes its type.1

   Breed (type object)              Monster (typed object)
   name, health, attack   <-------  breed
   new_monster()                    health   (its own data)
       ^
       |  one instance for each kind: goblin, dragon, wyvern, ...

Data that is specific to one instance is in the typed object. Data or behaviour that all instances of the same conceptual type share is in the type object. Objects that refer to the same type object function as if they were the same type.1 Johnson and Woolf called the pattern Type Object.23

Example

The example files show one program in each language. A Breed has a name, a starting health and an attack. A list of data defines three breeds, and no breed has its own class. new_monster is a constructor function on the breed, and each monster keeps a reference to its breed and its own health. The program prints:

goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
PythonGitHub
class Breed:
    def __init__(self, name, health, attack):
        self.name, self.health, self.attack = name, health, attack

    def new_monster(self):
        return Monster(self)


class Monster:
    def __init__(self, breed):
        self.breed = breed
        self.health = breed.health  # each monster has its own health

    def describe(self):
        b = self.breed
        return f"{b.name}: {self.health} health, attacks with {b.attack}"


# New kinds are data, for example from a file. No new class is needed.
table = [
    ("goblin", 20, "a dagger"),
    ("dragon", 200, "fire"),
    ("wyvern", 120, "its tail"),
]
breeds = [Breed(*row) for row in table]
for breed in breeds:
    print(breed.new_monster().describe())
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A class with one instance for each kind.
#include <iostream>
#include <string>
#include <vector>

class Monster;

class Breed {
public:
    Breed(std::string name, int health, std::string attack)
        : name_(std::move(name)), health_(health), attack_(std::move(attack)) {}
    Monster newMonster() const;
    const std::string& name() const { return name_; }
    int health() const { return health_; }
    const std::string& attack() const { return attack_; }

private:
    std::string name_;
    int health_;
    std::string attack_;
};

class Monster {
public:
    explicit Monster(const Breed& breed) : breed_(breed), health_(breed.health()) {}
    std::string describe() const {
        return breed_.name() + ": " + std::to_string(health_) +
               " health, attacks with " + breed_.attack();
    }

private:
    const Breed& breed_;  // the breed must live longer than the monster
    int health_;          // each monster has its own health
};

Monster Breed::newMonster() const { return Monster(*this); }

int main() {
    // New kinds are data, for example from a file.
    const std::vector<Breed> breeds = {
        {"goblin", 20, "a dagger"},
        {"dragon", 200, "fire"},
        {"wyvern", 120, "its tail"},
    };
    for (const Breed& b : breeds) {
        std::cout << b.newMonster().describe() << "\n";
    }
}
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A class with one instance for each kind. The program must keep each breed alive as long as its monsters.
JavaGitHub
import java.util.List;

public class Main {
    record Breed(String name, int health, String attack) {
        Monster newMonster() {
            return new Monster(this);
        }
    }

    static final class Monster {
        private final Breed breed;
        private int health; // each monster has its own health

        Monster(Breed breed) {
            this.breed = breed;
            this.health = breed.health();
        }

        String describe() {
            return breed.name() + ": " + health + " health, attacks with " + breed.attack();
        }
    }

    public static void main(String[] args) {
        // New kinds are data, for example from a file.
        List<Breed> breeds = List.of(
            new Breed("goblin", 20, "a dagger"),
            new Breed("dragon", 200, "fire"),
            new Breed("wyvern", 120, "its tail"));
        for (Breed b : breeds) {
            System.out.println(b.newMonster().describe());
        }
    }
}
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A record with one instance for each kind.
using System;

var breeds = new[]
{
    // New kinds are data, for example from a file.
    new Breed("goblin", 20, "a dagger"),
    new Breed("dragon", 200, "fire"),
    new Breed("wyvern", 120, "its tail"),
};
foreach (var b in breeds)
{
    Console.WriteLine(b.NewMonster().Describe());
}

record Breed(string Name, int Health, string Attack)
{
    public Monster NewMonster() => new Monster(this);
}

class Monster
{
    private readonly Breed breed;
    private int health; // each monster has its own health

    public Monster(Breed breed)
    {
        this.breed = breed;
        health = breed.Health;
    }

    public string Describe() =>
        $"{breed.Name}: {health} health, attacks with {breed.Attack}";
}
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A record with one instance for each kind.
JavaScriptGitHub
class Breed {
  constructor(name, health, attack) {
    this.name = name;
    this.health = health;
    this.attack = attack;
  }
  newMonster() {
    return new Monster(this);
  }
}

class Monster {
  constructor(breed) {
    this.breed = breed;
    this.health = breed.health; // each monster has its own health
  }
  describe() {
    const b = this.breed;
    return `${b.name}: ${this.health} health, attacks with ${b.attack}`;
  }
}

// New kinds are data, for example from a JSON file.
const table = [
  ["goblin", 20, "a dagger"],
  ["dragon", 200, "fire"],
  ["wyvern", 120, "its tail"],
];
for (const row of table) {
  console.log(new Breed(...row).newMonster().describe());
}
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A class with one instance for each kind.
TypeScriptGitHub
class Breed {
  name: string;
  health: number;
  attack: string;
  constructor(name: string, health: number, attack: string) {
    this.name = name;
    this.health = health;
    this.attack = attack;
  }
  newMonster(): Monster {
    return new Monster(this);
  }
}

class Monster {
  breed: Breed;
  health: number; // each monster has its own health
  constructor(breed: Breed) {
    this.breed = breed;
    this.health = breed.health;
  }
  describe(): string {
    const b = this.breed;
    return `${b.name}: ${this.health} health, attacks with ${b.attack}`;
  }
}

// New kinds are data, for example from a JSON file.
const table: [string, number, string][] = [
  ["goblin", 20, "a dagger"],
  ["dragon", 200, "fire"],
  ["wyvern", 120, "its tail"],
];
for (const [name, health, attack] of table) {
  console.log(new Breed(name, health, attack).newMonster().describe());
}
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A class with one instance for each kind.
package main

import "fmt"

type Breed struct {
	Name   string
	Health int
	Attack string
}

func (b *Breed) NewMonster() *Monster {
	return &Monster{breed: b, health: b.Health}
}

type Monster struct {
	breed  *Breed
	health int // each monster has its own health
}

func (m *Monster) Describe() string {
	return fmt.Sprintf("%s: %d health, attacks with %s", m.breed.Name, m.health, m.breed.Attack)
}

func main() {
	// New kinds are data, for example from a JSON file.
	breeds := []*Breed{
		{"goblin", 20, "a dagger"},
		{"dragon", 200, "fire"},
		{"wyvern", 120, "its tail"},
	}
	for _, b := range breeds {
		fmt.Println(b.NewMonster().Describe())
	}
}
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A struct with one value for each kind, and a pointer to it in each monster.
RustGitHub
struct Breed {
    name: String,
    health: u32,
    attack: String,
}

impl Breed {
    fn new_monster(&self) -> Monster<'_> {
        Monster { breed: self, health: self.health }
    }
}

struct Monster<'a> {
    breed: &'a Breed, // the breed must live longer than the monster
    health: u32,      // each monster has its own health
}

impl Monster<'_> {
    fn describe(&self) -> String {
        format!("{}: {} health, attacks with {}", self.breed.name, self.health, self.breed.attack)
    }
}

fn main() {
    // New kinds are data, for example from a file.
    let table = [("goblin", 20, "a dagger"), ("dragon", 200, "fire"), ("wyvern", 120, "its tail")];
    let breeds: Vec<Breed> = table
        .iter()
        .map(|&(n, h, a)| Breed { name: n.to_string(), health: h, attack: a.to_string() })
        .collect();
    for b in &breeds {
        println!("{}", b.new_monster().describe());
    }
}
Output
goblin: 20 health, attacks with a dagger
dragon: 200 health, attacks with fire
wyvern: 120 health, attacks with its tail
  • Verdict: idiom. A struct with one value for each kind. The monster borrows its breed.

Consequences

The benefits:1

  • Data and behaviour are shared across a set of similar objects, as with subclassing, but without a fixed set of hard-coded subclasses.
  • New types can come from data, for example from a file, so designers can add them without a programmer.

The costs:1

  • Manual tracking. The compiler keeps the classes of a program for you. With type objects, you must make sure that all of them are created and kept in memory as long as the typed objects need them, and that each new typed object refers to a valid type object.
  • Behaviour is harder to define. A subclass can override a method and do anything. A type object usually holds data. For behaviour, it can hold a pointer to one of a fixed set of functions, or the behaviour can be defined in data with the Interpreter or Bytecode patterns.

Data in the wrong place is a common error. Here the damage to one goblin is stored in the breed, so a new goblin starts with less health:

This code runs but gives a wrong answer on purpose.

class Breed:
    def __init__(self, name, health):
        self.name, self.health = name, health

    def new_monster(self):
        return Monster(self)


class Monster:
    def __init__(self, breed):
        self.breed = breed

    def take_damage(self, amount):
        self.breed.health -= amount  # changes every goblin


goblin = Breed("goblin", 20)
first = goblin.new_monster()
first.take_damage(5)
second = goblin.new_monster()
print("second goblin:", second.breed.health)  # meant to be 20
Output
second goblin: 15

When not to use it

  • The set of kinds is small and fixed, and each kind needs very different behaviour. Subclasses can override methods freely.1
  • The program depends on the bookkeeping that the compiler does for classes.1
  • Constructor on the type object. The type object can have a factory method that creates its typed objects. The type object then controls memory allocation, for example from an object pool.1
  • Change of type. An object can change its type object over time. For example, a dead monster can become a zombie by a change of its breed.1
  • Inheritance between type objects. With single inheritance, a type object has a parent. To get a value, the program might need to walk up the inheritance chain to the type that ultimately decides the value.1
class Breed:
    def __init__(self, name, parent=None, health=None, attack=None):
        self.name, self.parent = name, parent
        self._health, self._attack = health, attack

    def get(self, field):
        breed = self
        while getattr(breed, field) is None:  # walk up the chain
            breed = breed.parent
        return getattr(breed, field)

    @property
    def health(self):
        return self.get("_health")

    @property
    def attack(self):
        return self.get("_attack")


troll = Breed("troll", health=25, attack="a club")
archer = Breed("troll archer", parent=troll, attack="arrows")
print(f"{archer.name}: {archer.health} health, attacks with {archer.attack}")
Output
troll archer: 25 health, attacks with arrows
  • Flyweight. Both let instances share data. A flyweight saves memory, and its shared data need not be a type. A type object is for organization and flexibility.1
  • State. Both delegate part of an object to another object. A type object is usually what the object is; a state is what the object is now.1
  • Prototype. It solves the same high-level problem of sharing data and behaviour between objects in a different way.1

Known uses

  • In CPython, every pointer to a Python object can be cast to PyObject*, which the source calls "inheritance built by hand". Each object has a field ob_type, a pointer to a PyTypeObject.4 The type object struct _typeobject holds the type name, the sizes for allocation, and function pointers such as tp_repr.5
  • Nystrom says that C++ classes are the Type Object pattern applied to C: each instance has a pointer to the vtable of its class, as a monster has a reference to its breed.1

References

  1. Robert Nystrom, Game Programming Patterns, Type Object, Intent; Motivation; The Pattern; When to Use It; Keep in Mind; Design Decisions; See Also
  2. Robert Martin, Dirk Riehle and Frank Buschmann (editors), Pattern Languages of Program Design 3, Addison-Wesley, Chapter 4, Type Object, Ralph Johnson and Bobby Woolf
  3. Pattern Languages of Program Design 3, InformIT, Description; Table of Contents, I. General Purpose Design Patterns
  4. CPython v3.14.0 source, Include/object.h, struct _object and its comment, lines 104 to 145
  5. CPython v3.14.0 source, Include/cpython/object.h, struct _typeobject, lines 148 to 161

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7BMZQ3/text.yaml