Programming Search⌘K

Patternadvanced

Servant

Also called servant pattern, servant design pattern.

A servant is a class that gives one behaviour to a group of classes. The served objects implement a small interface, and the servant takes them as parameters.

Family
behavioral-design
Intent
Define a behaviour once in a servant class, and offer it to every class that implements the interface the servant requires.

Intent

The servant pattern defines an object used to offer some functionality to a group of classes without defining that functionality in each of them.1

Problem

Some objects must all do a common action. In the Wikipedia example, there are classes for geometric objects, such as a rectangle, an ellipse and a triangle, and each of them must move on a canvas.1

You can write a move method in each class. Then the same code is in many places. You can also put the method in a common parent class, but this is not always possible.1 The paper says: "When we want some objects to perform a common action, it is often not the best solution to define this action as a method in every class."2

Solution

Define a special class, the servant, that serves all these objects and provides the common functionality.2 The servant needs some abilities from the served objects. An interface states these requirements, and each served class implements it.2

   User ------------> MoveServant
                        move_to(movable, where)
                        move_by(movable, dx, dy)
                             |
                             | uses only the interface
                             v
                      <<interface>> Movable
                        get_position()
                        set_position(p)
                        ^      ^       ^
               Rectangle   Ellipse   Triangle

In the example, the interface Movable has the methods getPosition and setPosition. The servant MoveServant has the methods moveTo and moveBy. It can move every object that implements Movable, so the moving code appears in only one class.1

Example

The example files show one program in each language. Three shapes implement Movable. One MoveServant moves all of them, and no shape has its own move code. The program prints:

rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
PythonGitHub
from typing import Protocol


class Movable(Protocol):
    def get_position(self) -> tuple[int, int]: ...
    def set_position(self, p: tuple[int, int]) -> None: ...


class MoveServant:
    """The moving code is here, in one class only."""

    def move_to(self, serviced: Movable, where: tuple[int, int]) -> None:
        serviced.set_position(where)

    def move_by(self, serviced: Movable, dx: int, dy: int) -> None:
        x, y = serviced.get_position()
        serviced.set_position((x + dx, y + dy))


class Shape:
    def __init__(self, name: str, position: tuple[int, int]):
        self.name, self._position = name, position

    def get_position(self) -> tuple[int, int]:
        return self._position

    def set_position(self, p: tuple[int, int]) -> None:
        self._position = p

    def __str__(self) -> str:
        return f"{self.name} at ({self._position[0]}, {self._position[1]})"


class Rectangle(Shape): pass
class Ellipse(Shape): pass
class Triangle(Shape): pass


servant = MoveServant()
shapes = [Rectangle("rectangle", (0, 0)), Ellipse("ellipse", (10, 0)), Triangle("triangle", (0, 10))]
for s in shapes:
    servant.move_by(s, 3, 4)
    print(s)
servant.move_to(shapes[2], (1, 1))
print(shapes[2])
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. A typing.Protocol states what the servant needs, and any class with the two methods can be served.
#include <iostream>
#include <string>
#include <vector>

struct Position {
    int x, y;
};

class Movable {
public:
    virtual ~Movable() = default;
    virtual Position getPosition() const = 0;
    virtual void setPosition(Position p) = 0;
};

class MoveServant {
public:
    void moveTo(Movable& serviced, Position where) const { serviced.setPosition(where); }
    void moveBy(Movable& serviced, int dx, int dy) const {
        Position p = serviced.getPosition();
        serviced.setPosition({p.x + dx, p.y + dy});
    }
};

class Shape : public Movable {
public:
    Shape(std::string name, Position p) : name_(std::move(name)), p_(p) {}
    Position getPosition() const override { return p_; }
    void setPosition(Position p) override { p_ = p; }
    std::string str() const {
        return name_ + " at (" + std::to_string(p_.x) + ", " + std::to_string(p_.y) + ")";
    }

private:
    std::string name_;
    Position p_;
};

struct Rectangle : Shape { explicit Rectangle(Position p) : Shape("rectangle", p) {} };
struct Ellipse : Shape { explicit Ellipse(Position p) : Shape("ellipse", p) {} };
struct Triangle : Shape { explicit Triangle(Position p) : Shape("triangle", p) {} };

int main() {
    MoveServant servant;
    Rectangle r({0, 0});
    Ellipse e({10, 0});
    Triangle t({0, 10});
    std::vector<Shape*> shapes = {&r, &e, &t};
    for (Shape* s : shapes) {
        servant.moveBy(*s, 3, 4);
        std::cout << s->str() << "\n";
    }
    servant.moveTo(t, {1, 1});
    std::cout << t.str() << "\n";
}
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. An abstract class Movable states what the servant needs.
JavaGitHub
import java.util.List;

public class Main {
    record Position(int x, int y) {}

    interface Movable {
        Position getPosition();
        void setPosition(Position p);
    }

    static final class MoveServant {
        void moveTo(Movable serviced, Position where) {
            serviced.setPosition(where);
        }

        void moveBy(Movable serviced, int dx, int dy) {
            Position p = serviced.getPosition();
            serviced.setPosition(new Position(p.x() + dx, p.y() + dy));
        }
    }

    static class Shape implements Movable {
        private final String name;
        private Position p;

        Shape(String name, Position p) {
            this.name = name;
            this.p = p;
        }

        public Position getPosition() { return p; }
        public void setPosition(Position p) { this.p = p; }

        @Override
        public String toString() { return name + " at (" + p.x() + ", " + p.y() + ")"; }
    }

    static final class Rectangle extends Shape { Rectangle(Position p) { super("rectangle", p); } }
    static final class Ellipse extends Shape { Ellipse(Position p) { super("ellipse", p); } }
    static final class Triangle extends Shape { Triangle(Position p) { super("triangle", p); } }

    public static void main(String[] args) {
        MoveServant servant = new MoveServant();
        List<Shape> shapes = List.of(
            new Rectangle(new Position(0, 0)), new Ellipse(new Position(10, 0)), new Triangle(new Position(0, 10)));
        for (Shape s : shapes) {
            servant.moveBy(s, 3, 4);
            System.out.println(s);
        }
        servant.moveTo(shapes.get(2), new Position(1, 1));
        System.out.println(shapes.get(2));
    }
}
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. The interface Movable states what the servant needs, as in the Wikipedia example.
using System;

var servant = new MoveServant();
Shape[] shapes = { new Rectangle(new(0, 0)), new Ellipse(new(10, 0)), new Triangle(new(0, 10)) };
foreach (var s in shapes)
{
    servant.MoveBy(s, 3, 4);
    Console.WriteLine(s);
}
servant.MoveTo(shapes[2], new(1, 1));
Console.WriteLine(shapes[2]);

record Position(int X, int Y);

interface IMovable
{
    Position Position { get; set; }
}

class MoveServant
{
    public void MoveTo(IMovable serviced, Position where) => serviced.Position = where;

    public void MoveBy(IMovable serviced, int dx, int dy) =>
        serviced.Position = new Position(serviced.Position.X + dx, serviced.Position.Y + dy);
}

abstract class Shape : IMovable
{
    private readonly string name;
    protected Shape(string name, Position p) { this.name = name; Position = p; }
    public Position Position { get; set; }
    public override string ToString() => $"{name} at ({Position.X}, {Position.Y})";
}

class Rectangle : Shape { public Rectangle(Position p) : base("rectangle", p) { } }
class Ellipse : Shape { public Ellipse(Position p) : base("ellipse", p) { } }
class Triangle : Shape { public Triangle(Position p) : base("triangle", p) { } }
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. The interface IMovable states what the servant needs. Here it is a property, not two methods.
JavaScriptGitHub
// The servant needs getPosition and setPosition from each served object.
class MoveServant {
  moveTo(serviced, where) {
    serviced.setPosition(where);
  }
  moveBy(serviced, dx, dy) {
    const [x, y] = serviced.getPosition();
    serviced.setPosition([x + dx, y + dy]);
  }
}

class Shape {
  #position;
  constructor(name, position) {
    this.name = name;
    this.#position = position;
  }
  getPosition() { return this.#position; }
  setPosition(p) { this.#position = p; }
  toString() { return `${this.name} at (${this.#position[0]}, ${this.#position[1]})`; }
}
class Rectangle extends Shape {}
class Ellipse extends Shape {}
class Triangle extends Shape {}

const servant = new MoveServant();
const shapes = [new Rectangle("rectangle", [0, 0]), new Ellipse("ellipse", [10, 0]), new Triangle("triangle", [0, 10])];
for (const s of shapes) {
  servant.moveBy(s, 3, 4);
  console.log(String(s));
}
servant.moveTo(shapes[2], [1, 1]);
console.log(String(shapes[2]));
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. The interface is a convention: each served object has getPosition and setPosition.
TypeScriptGitHub
type Position = [number, number];

interface Movable {
  getPosition(): Position;
  setPosition(p: Position): void;
}

class MoveServant {
  moveTo(serviced: Movable, where: Position): void {
    serviced.setPosition(where);
  }
  moveBy(serviced: Movable, dx: number, dy: number): void {
    const [x, y] = serviced.getPosition();
    serviced.setPosition([x + dx, y + dy]);
  }
}

class Shape implements Movable {
  name: string;
  private position: Position;
  constructor(name: string, position: Position) {
    this.name = name;
    this.position = position;
  }
  getPosition(): Position { return this.position; }
  setPosition(p: Position): void { this.position = p; }
  toString(): string { return `${this.name} at (${this.position[0]}, ${this.position[1]})`; }
}
class Rectangle extends Shape {}
class Ellipse extends Shape {}
class Triangle extends Shape {}

const servant = new MoveServant();
const shapes: Shape[] = [new Rectangle("rectangle", [0, 0]), new Ellipse("ellipse", [10, 0]), new Triangle("triangle", [0, 10])];
for (const s of shapes) {
  servant.moveBy(s, 3, 4);
  console.log(String(s));
}
servant.moveTo(shapes[2], [1, 1]);
console.log(String(shapes[2]));
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. The interface Movable states what the servant needs.
package main

import "fmt"

type Position struct{ X, Y int }

type Movable interface {
	Position() Position
	SetPosition(p Position)
}

type MoveServant struct{}

func (MoveServant) MoveTo(m Movable, where Position) { m.SetPosition(where) }

func (MoveServant) MoveBy(m Movable, dx, dy int) {
	p := m.Position()
	m.SetPosition(Position{p.X + dx, p.Y + dy})
}

type Shape struct {
	name string
	pos  Position
}

func (s *Shape) Position() Position     { return s.pos }
func (s *Shape) SetPosition(p Position) { s.pos = p }
func (s *Shape) String() string         { return fmt.Sprintf("%s at (%d, %d)", s.name, s.pos.X, s.pos.Y) }

type Rectangle struct{ Shape }
type Ellipse struct{ Shape }
type Triangle struct{ Shape }

func main() {
	var servant MoveServant
	r := &Rectangle{Shape{"rectangle", Position{0, 0}}}
	e := &Ellipse{Shape{"ellipse", Position{10, 0}}}
	t := &Triangle{Shape{"triangle", Position{0, 10}}}
	for _, m := range []Movable{r, e, t} {
		servant.MoveBy(m, 3, 4)
		fmt.Println(m)
	}
	servant.MoveTo(t, Position{1, 1})
	fmt.Println(t)
}
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. A type is served when it has the methods of Movable. The package sort uses this form.
RustGitHub
use std::fmt;

#[derive(Clone, Copy)]
struct Position {
    x: i32,
    y: i32,
}

trait Movable {
    fn position(&self) -> Position;
    fn set_position(&mut self, p: Position);
}

struct MoveServant;

impl MoveServant {
    fn move_to(&self, m: &mut dyn Movable, where_: Position) {
        m.set_position(where_);
    }
    fn move_by(&self, m: &mut dyn Movable, dx: i32, dy: i32) {
        let p = m.position();
        m.set_position(Position { x: p.x + dx, y: p.y + dy });
    }
}

struct Shape {
    name: &'static str,
    pos: Position,
}

impl Movable for Shape {
    fn position(&self) -> Position {
        self.pos
    }
    fn set_position(&mut self, p: Position) {
        self.pos = p;
    }
}

impl fmt::Display for Shape {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} at ({}, {})", self.name, self.pos.x, self.pos.y)
    }
}

fn main() {
    let servant = MoveServant;
    let mut shapes = [
        Shape { name: "rectangle", pos: Position { x: 0, y: 0 } },
        Shape { name: "ellipse", pos: Position { x: 10, y: 0 } },
        Shape { name: "triangle", pos: Position { x: 0, y: 10 } },
    ];
    for s in shapes.iter_mut() {
        servant.move_by(s, 3, 4);
        println!("{}", s);
    }
    servant.move_to(&mut shapes[2], Position { x: 1, y: 1 });
    println!("{}", shapes[2]);
}
Output
rectangle at (3, 4)
ellipse at (13, 4)
triangle at (3, 14)
triangle at (1, 1)
  • Verdict: idiom. A trait Movable states what the servant needs.

Consequences

The benefits:

  • The common behaviour is in one class.1 A change to the behaviour is made in one place.
  • The served classes need not have a common parent class. They need only implement the interface.1
  • The served classes do not have to know about the servant, in the first form of the pattern.1

The costs:

  • The servant can use only what the interface gives. The served classes must make that data public through the interface, for example the position of a shape.1
  • There is one more class and one more interface to understand.

Without a servant, each class has its own copy of the code, and the copies can become different. Here the ellipse copy has an error, and only the ellipse moves the wrong way:

This code runs but gives a wrong answer on purpose.

class Rectangle:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def move_by(self, dx, dy):
        self.x, self.y = self.x + dx, self.y + dy


class Ellipse:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def move_by(self, dx, dy):
        self.x, self.y = self.x + dx, self.y - dy  # a copy with an error


for shape in [Rectangle(0, 0), Ellipse(10, 0)]:
    shape.move_by(3, 4)
    print(type(shape).__name__.lower(), f"at ({shape.x}, {shape.y})")
Output
rectangle at (3, 4)
ellipse at (13, -4)

When not to use it

  • Only one class needs the behaviour. Then a method in that class is simpler.
  • The behaviour needs private data of each class that the class must not make public.
  • A common parent class can hold the behaviour, and the classes already share that parent.1

There are two ways to implement the pattern:1

  1. The user knows the servant. It calls the servant and gives it the served objects as parameters. The served classes do not know about the servant.
  2. The served objects know the servant. The user calls the served objects, and they ask the servant to do the work.

The second form looks like this. The user calls move_by on the shape, and the shape sends the request to the servant:

class MoveServant:
    def move_by(self, movable, dx, dy):
        x, y = movable.get_position()
        movable.set_position((x + dx, y + dy))


SERVANT = MoveServant()


class Triangle:
    def __init__(self, position):
        self._position = position

    def get_position(self):
        return self._position

    def set_position(self, position):
        self._position = position

    def move_by(self, dx, dy):
        SERVANT.move_by(self, dx, dy)  # the shape asks the servant


t = Triangle((0, 10))
t.move_by(3, 4)
print("triangle at", t.get_position())
Output
triangle at (3, 14)
  • Command. The two patterns are very similar, and implementations of them are often virtually the same. The difference is the approach to the problem. With Servant, a class offers functionality, and the served objects are passed to it. With Command, command objects are passed to the original objects as parameters of their methods.1 The 2006 paper calls Servant in reality another type of Command.2 Its teaching example is a servant Repeater with a method repeat(int, Command) that calls command() of its second parameter the given number of times.2

Known uses

  • Go's package sort has the interface sort.Interface with the methods Len, Less and Swap. The comment says that an implementation of Interface can be sorted by the routines in the package. The function Sort(data Interface) sorts any such value, so the sorted types do not contain sort code.3
  • Java's class java.util.Collections consists exclusively of static methods that operate on or return collections. Its method sort(List) requires that all elements in the list implement the Comparable interface.4

References

  1. Servant (design pattern), Wikipedia, lead; Description and simple example; Two ways of implementation; Similar design pattern, Command
  2. Rudolf Pecinovský, Jarmila Pavlíčková and Luboš Pavlíček, Let's Modify the Objects-First Approach into Design-Patterns-First, ITiCSE 2006, section 3, Second lesson; section 3.3, Introducing interface; section 4.1
  3. Go go1.25.0 source, src/sort/sort.go, type Interface and func Sort, lines 15 to 50
  4. Java SE 25 API, java.util.Collections, class description; sort(List)

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