Programming Search⌘K

Patternresearch

Twin

Also called twin pattern, twin object, twin class.

The Twin pattern models multiple inheritance in a language that has only single inheritance. Two linked objects each inherit from one parent, and together they act as one object.

Family
structural-design
Intent
Model multiple inheritance in a language without it: give each parent its own subclass, link the two subclass objects by fields, and let them act as one twin object.

Intent

Twin is a structural pattern for languages with single inheritance, such as Java and Oberon-2. It models a class that inherits from two parents, and it avoids many of the problems of multiple inheritance.1

Problem

A class sometimes needs the data and code of two parent classes. Mössenböck's example is a ball game. All game items inherit from GameItem, which gives them methods to draw themselves and to check collisions. A ball is also an active object, so it must also inherit from Thread, which a scheduler runs.1

In Java, the extends clause of a class names one class type, its direct superclass.2 A class Ball cannot extend both GameItem and Thread.

Solution

Instead of one child class with two parents, make two child classes. Each child class inherits from one of the parents. The two child objects are linked by fields, so they can be seen as one twin object with two ends.3

   GameItem                    Thread
   (Parent1)                   (Parent2)
      ^                           ^
      |                           |
   BallItem  ---- twin ---->  BallThread
   (Child1)  <---- twin ----  (Child2)
   new fields and methods      overrides of Thread methods

The participants work as follows:1

  • Each child class is responsible for the protocol that it inherits from its parent. It handles the messages of this protocol and forwards other messages to its partner.
  • A client refers to one twin directly, for example ballItem, and to the other through its twin field, for example ballItem.twin.
  • A client that uses the protocol of one parent talks to the child of that parent. The game board talks to BallItem, and the scheduler talks to BallThread.
  • New methods and fields are usually declared in one child only.

Example

The example files show one program in each language. Item is a game item that prints its position with a template method show. Ticker counts ticks and calls a hook on_tick at each tick. A ball needs both parents, so BallItem extends Item, BallTicker extends Ticker, and each holds a reference to the other. Each tick moves the ball by 2. The program prints:

ball at 0
ball at 2
ball at 4
ticks: 2

C++ has multiple inheritance, Go has struct embedding, and Rust has traits with default methods, so their files show the direct form instead of a twin.

PythonGitHub
class Item:
    def __init__(self, name):
        self.name = name

    def show(self):  # template method: position() comes from the subclass
        print(f"{self.name} at {self.position()}")


class Ticker:
    def __init__(self):
        self.count = 0

    def tick(self):
        self.count += 1
        self.on_tick()


class BallItem(Item):
    def __init__(self, name):
        super().__init__(name)
        self.x = 0
        self.twin = BallTicker(self)

    def position(self):
        return self.x

    def move(self):
        self.x += 2


class BallTicker(Ticker):
    def __init__(self, twin):
        super().__init__()
        self.twin = twin

    def on_tick(self):
        self.twin.move()


ball = BallItem("ball")
ball.show()
for _ in range(2):
    ball.twin.tick()
    ball.show()
print(f"ticks: {ball.twin.count}")
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: idiom. Python has multiple inheritance, so class Ball(Item, Ticker) also works. The twin form keeps the names of the two parents apart.
#include <iostream>
#include <string>
#include <utility>

class Item {
public:
    explicit Item(std::string name) : name_(std::move(name)) {}
    virtual ~Item() = default;
    void show() const { std::cout << name_ << " at " << position() << "\n"; }

private:
    virtual int position() const = 0;
    std::string name_;
};

class Ticker {
public:
    virtual ~Ticker() = default;
    void tick() {
        ++count_;
        on_tick();
    }
    int count() const { return count_; }

private:
    virtual void on_tick() = 0;
    int count_ = 0;
};

// C++ has multiple inheritance, so one class has both parents.
class Ball : public Item, public Ticker {
public:
    explicit Ball(std::string name) : Item(std::move(name)) {}

private:
    int position() const override { return x_; }
    void on_tick() override { x_ += 2; }
    int x_ = 0;
};

int main() {
    Ball ball("ball");
    ball.show();
    for (int i = 0; i < 2; ++i) {
        ball.tick();
        ball.show();
    }
    std::cout << "ticks: " << ball.count() << "\n";
}
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: native. C++ has multiple inheritance, so Ball derives from both Item and Ticker, and a twin is not needed.
JavaGitHub
abstract class Item {
    final String name;
    Item(String name) { this.name = name; }
    abstract int position();
    void show() { System.out.println(name + " at " + position()); }
}

abstract class Ticker {
    int count;
    abstract void onTick();
    void tick() { count++; onTick(); }
}

class BallItem extends Item {
    int x;
    final BallTicker twin;
    BallItem(String name) { super(name); twin = new BallTicker(this); }
    int position() { return x; }
    void move() { x += 2; }
}

class BallTicker extends Ticker {
    final BallItem twin;
    BallTicker(BallItem twin) { this.twin = twin; }
    void onTick() { twin.move(); }
}

public class Main {
    public static void main(String[] args) {
        BallItem ball = new BallItem("ball");
        ball.show();
        for (int i = 0; i < 2; i++) {
            ball.twin.tick();
            ball.show();
        }
        System.out.println("ticks: " + ball.twin.count);
    }
}
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: idiom. The extends clause names one direct superclass, so Twin is the form that Mössenböck gives for Java. The two classes share a package, so they can use each other's package-private fields.
using System;

abstract class Item
{
    public readonly string Name;
    protected Item(string name) { Name = name; }
    public abstract int Position();
    public void Show() => Console.WriteLine($"{Name} at {Position()}");
}

abstract class Ticker
{
    public int Count;
    protected abstract void OnTick();
    public void Tick() { Count++; OnTick(); }
}

class BallItem : Item
{
    public int X;
    public readonly BallTicker Twin;
    public BallItem(string name) : base(name) { Twin = new BallTicker(this); }
    public override int Position() => X;
    public void Move() => X += 2;
}

class BallTicker : Ticker
{
    private readonly BallItem twin;
    public BallTicker(BallItem twin) { this.twin = twin; }
    protected override void OnTick() => twin.Move();
}

class Program
{
    static void Main()
    {
        var ball = new BallItem("ball");
        ball.Show();
        for (int i = 0; i < 2; i++)
        {
            ball.Twin.Tick();
            ball.Show();
        }
        Console.WriteLine($"ticks: {ball.Twin.Count}");
    }
}
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: idiom. A class has one base class and can implement several interfaces, so the code of a second parent needs a twin.
JavaScriptGitHub
class Item {
  constructor(name) {
    this.name = name;
  }
  show() {
    console.log(`${this.name} at ${this.position()}`);
  }
}

class Ticker {
  constructor() {
    this.count = 0;
  }
  tick() {
    this.count += 1;
    this.onTick();
  }
}

class BallItem extends Item {
  constructor(name) {
    super(name);
    this.x = 0;
    this.twin = new BallTicker(this);
  }
  position() {
    return this.x;
  }
  move() {
    this.x += 2;
  }
}

class BallTicker extends Ticker {
  constructor(twin) {
    super();
    this.twin = twin;
  }
  onTick() {
    this.twin.move();
  }
}

const ball = new BallItem("ball");
ball.show();
for (let i = 0; i < 2; i++) {
  ball.twin.tick();
  ball.show();
}
console.log(`ticks: ${ball.twin.count}`);
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: idiom. A class has one extends clause, so the two parents need two linked objects.
TypeScriptGitHub
abstract class Item {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  abstract position(): number;
  show(): void {
    console.log(`${this.name} at ${this.position()}`);
  }
}

abstract class Ticker {
  count = 0;
  abstract onTick(): void;
  tick(): void {
    this.count += 1;
    this.onTick();
  }
}

class BallItem extends Item {
  x = 0;
  twin: BallTicker;
  constructor(name: string) {
    super(name);
    this.twin = new BallTicker(this);
  }
  position(): number {
    return this.x;
  }
  move(): void {
    this.x += 2;
  }
}

class BallTicker extends Ticker {
  twin: BallItem;
  constructor(twin: BallItem) {
    super();
    this.twin = twin;
  }
  onTick(): void {
    this.twin.move();
  }
}

const ball = new BallItem("ball");
ball.show();
for (let i = 0; i < 2; i++) {
  ball.twin.tick();
  ball.show();
}
console.log(`ticks: ${ball.twin.count}`);
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: idiom. A class extends one class and can implement several interfaces, so the code of a second parent needs a twin.
package main

import "fmt"

type Item struct {
	name     string
	position func() int
}

func (i *Item) Show() { fmt.Printf("%s at %d\n", i.name, i.position()) }

type Ticker struct {
	count  int
	onTick func()
}

func (t *Ticker) Tick() {
	t.count++
	t.onTick()
}

// Ball embeds both parts, so it has the methods of both.
type Ball struct {
	Item
	Ticker
	x int
}

func NewBall(name string) *Ball {
	b := &Ball{}
	b.Item = Item{name: name, position: func() int { return b.x }}
	b.Ticker = Ticker{onTick: func() { b.x += 2 }}
	return b
}

func main() {
	ball := NewBall("ball")
	ball.Show()
	for i := 0; i < 2; i++ {
		ball.Tick()
		ball.Show()
	}
	fmt.Printf("ticks: %d\n", ball.count)
}
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: idiom. Go has no inheritance. A struct can embed several structs, and their methods are promoted to it, so one value has the methods of both parts. The hooks are function fields, because an embedded struct does not call methods of the outer struct.
RustGitHub
trait Item {
    fn name(&self) -> &str;
    fn position(&self) -> i32;
    fn show(&self) {
        println!("{} at {}", self.name(), self.position());
    }
}

trait Ticker {
    fn count_mut(&mut self) -> &mut u32;
    fn on_tick(&mut self);
    fn tick(&mut self) {
        *self.count_mut() += 1;
        self.on_tick();
    }
}

struct Ball {
    name: String,
    x: i32,
    count: u32,
}

impl Item for Ball {
    fn name(&self) -> &str {
        &self.name
    }
    fn position(&self) -> i32 {
        self.x
    }
}

impl Ticker for Ball {
    fn count_mut(&mut self) -> &mut u32 {
        &mut self.count
    }
    fn on_tick(&mut self) {
        self.x += 2;
    }
}

fn main() {
    let mut ball = Ball { name: "ball".to_string(), x: 0, count: 0 };
    ball.show();
    for _ in 0..2 {
        ball.tick();
        ball.show();
    }
    println!("ticks: {}", ball.count);
}
Output
ball at 0
ball at 2
ball at 4
ticks: 2
  • Verdict: idiom. Rust has no inheritance. One type implements several traits, and each trait can give default methods, so the code of both parents goes to one type without a twin.

Consequences

The benefits:1

  • A single-inheritance language gets most of the benefits of multiple inheritance.
  • Each child keeps the names of its own parent, so the name clashes of multiple inheritance do not occur.

The costs:

  • Forwarding. Twin replaces inheritance relations with composition. Messages must be forwarded, and forwarding is less efficient than inheritance.1
  • Close coupling. The two children often need each other's private fields and methods. In Java, the children can share a package and use package visibility. In Modula-3 and Oberon, they can share a module.1
  • Subclassing. It is often sufficient to subclass one twin. The subclass is then compatible with that twin only, not with its partner.1

Here the twin is subclassed on the item side only. FastBall overrides on_tick to move by 5, but the ticker calls its own on_tick, so the override has no effect:

This code runs but gives a wrong answer on purpose.

class Item:
    def __init__(self, name):
        self.name = name

    def show(self):
        print(f"{self.name} at {self.position()}")


class Ticker:
    def tick(self):
        self.on_tick()


class BallItem(Item):
    def __init__(self, name):
        super().__init__(name)
        self.x = 0
        self.twin = BallTicker(self)

    def position(self):
        return self.x

    def on_tick(self):  # a copy of the Ticker protocol, for subclasses
        self.twin.on_tick()


class BallTicker(Ticker):
    def __init__(self, twin):
        self.twin = twin

    def on_tick(self):
        self.twin.x += 2


class FastBall(BallItem):
    def on_tick(self):  # meant to move by 5
        self.x += 5


ball = FastBall("fast ball")
ball.twin.tick()  # the scheduler holds the ticker end of the twin
ball.show()
Output
fast ball at 2

One fix is to keep the behaviour in the child that has the new fields and to let the other child forward to it. A subclass of that child then changes the behaviour for both ends:

class Item:
    def __init__(self, name):
        self.name = name

    def show(self):
        print(f"{self.name} at {self.position()}")


class Ticker:
    def tick(self):
        self.on_tick()


class BallItem(Item):
    def __init__(self, name):
        super().__init__(name)
        self.x = 0
        self.twin = BallTicker(self)

    def position(self):
        return self.x

    def move(self):
        self.x += 2


class BallTicker(Ticker):
    def __init__(self, twin):
        self.twin = twin

    def on_tick(self):
        self.twin.move()  # forward to the partner


class FastBall(BallItem):
    def move(self):
        self.x += 5


ball = FastBall("fast ball")
ball.twin.tick()
ball.show()
Output
fast ball at 5

The other fix is to make the subclass a twin again, with one grandchild for each child.1

When not to use it

  • The language has multiple inheritance, traits or mixins that solve the problem directly.
  • The class needs only the type of the second parent, not its code. In Java, the class can then extend one class and implement an interface, as MyApplet extends Applet implements MouseListener does in Mössenböck's paper.1
  • More than two parents. Twin extends to three or more parents, with one child for each parent and links between all children. This is much more complex than multiple inheritance.1

Inner class. In Java, one twin can be an inner class of the other. The inner object can then use all private fields of the outer object, and no explicit link is necessary. The solution is not symmetric: the outer class cannot use the private fields of the inner class.1

Adapter. Twin is related to the two-way Adapter pattern of Gamma and his coauthors, which lets two clients view one object differently. The two-way adapter uses multiple inheritance, and Twin avoids it.1

Delegation. Each twin forwards the messages that it does not handle to its partner, as in the Delegation pattern.1

Mixin. In a language with mixins, a Mixin gives a class the code of a second class without a twin.

Known uses

  • Oberon-2: the ball game of the motivating example was a teaching exercise. In the Oberon system, a ball was a process and also a game object.1
  • Java applets: an applet extends Applet. A partner MyAppletListener extends a standard listener class StdMouseListener, and each holds a link to the other.1
  • Java Swing: JComponent.java at jdk-21-ga has the inner class form. JComponent extends Container, and its inner class AccessibleJComponent extends AccessibleAWTContainer. Its getToolTipText method forwards to JComponent.this.getToolTipText().4

References

  1. Hanspeter Mössenböck, Twin: A Design Pattern for Modeling Multiple Inheritance, University of Linz, sections 1 to 10 and Acknowledgements
  2. The Java Language Specification, Java SE 25 Edition, 8.1.4 Superclasses and Subclasses, 8.1.4, ClassExtends
  3. Twin pattern, Wikipedia, Introduction; Definition; Collaborations
  4. OpenJDK jdk-21-ga source, javax/swing/JComponent.java, JComponent at line 229, AccessibleJComponent at lines 3736 to 3745, getToolTipText at lines 4038 to 4040

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/T8KY09/text.yaml