Programming Search⌘K

Patterncore

Plugin

Also called Plugin pattern, plug-in, runtime linking by configuration.

A plugin factory reads a configuration when the program starts and creates the implementation that it names, so the program links classes during configuration and not at compile time.

Family
architectural
Intent
Link classes during configuration rather than compilation.

Intent

A plugin "Links classes during configuration rather than compilation."1 The code uses an interface. A configuration, which is read when the program starts, names the class that implements it. A plugin factory creates that class.

Problem

A Separated interface lets one interface have several implementations, for example a key generator that is a counter in memory for unit tests and a database sequence in production. Something must choose the implementation. The usual answer is a factory with a conditional statement that tests the mode of the program.

With many factories, each one has its own conditional. A new deployment, such as tests against an in-memory database, needs a change in each factory, then a new build and a new deployment. The catalog says: "Configuration shouldn't be scattered throughout your application, nor should it require a rebuild or redeployment."1

Solution

"Plugin solves both problems by providing centralized, runtime configuration."1 The parts are:

  • The interface. The code uses only the interface, such as KeyGenerator.
  • The implementations. Each one implements the interface. The code that uses the interface does not import them.
  • The configuration. For each deployment, a file or a table maps each interface to the name of an implementation. It is the only place that names the classes.
  • The plugin factory. It reads the configuration, finds the class by its name, creates an object and checks that the object implements the interface. A language with reflection loads the class by name. In other languages, each plugin registers a constructor under its name.
  test.config:        KeyGenerator = CounterKeyGenerator
  production.config:  KeyGenerator = SequenceKeyGenerator
  code:  PluginFactory(config).get("KeyGenerator")  -->  a KeyGenerator

In the following program, the configuration names a function as module:attribute, and load imports the module and gets the function. This is the form that Python entry points use.2

import importlib


def load(reference):  # "module:attribute", the form of a Python entry point
    module_name, _, attribute = reference.partition(":")
    return getattr(importlib.import_module(module_name), attribute)


for configured in ["json:dumps", "pprint:pformat"]:  # read from a configuration file
    serialize = load(configured)
    print(configured, "->", serialize({"id": 7}))
Output
json:dumps -> {"id": 7}
pprint:pformat -> {'id': 7}

Example

Each example has a KeyGenerator interface with two implementations: CounterKeyGenerator for tests and SequenceKeyGenerator, which stands for a database sequence, for production. Three configurations name the implementation. The program gives each configuration to a PluginFactory and asks for three keys. The test configuration gives keys 1 to 3 and the production configuration gives keys 1001 to 1003. The third configuration names a class that does not exist, and the factory gives a clear error.

PythonGitHub
import importlib


class CounterKeyGenerator:  # for unit tests: a counter in memory
    def __init__(self):
        self.last = 0

    def next_key(self):
        self.last += 1
        return self.last


class SequenceKeyGenerator:  # for production: it stands for a database sequence
    def __init__(self):
        self.last = 1000

    def next_key(self):
        self.last += 1
        return self.last


# One configuration for each deployment. Only the configuration names the classes.
CONFIGS = {
    "test": {"KeyGenerator": "__main__:CounterKeyGenerator"},
    "production": {"KeyGenerator": "__main__:SequenceKeyGenerator"},
    "broken": {"KeyGenerator": "__main__:FileKeyGenerator"},
}


class PluginFactory:
    def __init__(self, config):
        self.config = config

    def get(self, interface):
        module_name, _, class_name = self.config[interface].partition(":")
        cls = getattr(importlib.import_module(module_name), class_name, None)
        if cls is None:
            raise LookupError(f"no plugin named {class_name}")
        return cls()


for name, config in CONFIGS.items():
    try:
        gen = PluginFactory(config).get("KeyGenerator")
    except LookupError as e:
        print(f"{name}: error: {e}")
        continue
    keys = ", ".join(str(gen.next_key()) for _ in range(3))
    print(f"{name}: keys {keys} from {type(gen).__name__}")
Output
test: keys 1, 2, 3 from CounterKeyGenerator
production: keys 1001, 1002, 1003 from SequenceKeyGenerator
broken: error: no plugin named FileKeyGenerator
  • Verdict: stdlib. importlib.import_module and getattr load a class from a reference of the form module:attribute, which is the form of an entry point. Installed packages can publish such references as entry points, and importlib.metadata.entry_points finds them.
  • The configuration names the module __main__ here because the example is one file. In a real program, each plugin is in its own module.
JavaGitHub
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public interface KeyGenerator {
        long nextKey();
    }

    // For unit tests: a counter in memory.
    public static class CounterKeyGenerator implements KeyGenerator {
        private long last = 0;
        public long nextKey() { return ++last; }
    }

    // For production: it stands for a database sequence.
    public static class SequenceKeyGenerator implements KeyGenerator {
        private long last = 1000;
        public long nextKey() { return ++last; }
    }

    static class PluginFactory {
        private final Map<String, String> config;
        PluginFactory(Map<String, String> config) { this.config = config; }

        // Load the class that the configuration names, and check that it implements the interface.
        <T> T get(Class<T> iface) {
            String className = config.get(iface.getSimpleName());
            try {
                Class<?> c = Class.forName(className);
                return iface.cast(c.getDeclaredConstructor().newInstance());
            } catch (ReflectiveOperationException e) {
                String simple = className.substring(className.lastIndexOf('$') + 1);
                throw new IllegalStateException("no plugin named " + simple, e);
            }
        }
    }

    public static void main(String[] args) {
        // One configuration for each deployment. Only the configuration names the classes.
        Map<String, Map<String, String>> configs = new LinkedHashMap<>();
        configs.put("test", Map.of("KeyGenerator", "Main$CounterKeyGenerator"));
        configs.put("production", Map.of("KeyGenerator", "Main$SequenceKeyGenerator"));
        configs.put("broken", Map.of("KeyGenerator", "Main$FileKeyGenerator"));

        for (var entry : configs.entrySet()) {
            KeyGenerator gen;
            try {
                gen = new PluginFactory(entry.getValue()).get(KeyGenerator.class);
            } catch (IllegalStateException e) {
                System.out.println(entry.getKey() + ": error: " + e.getMessage());
                continue;
            }
            String keys = gen.nextKey() + ", " + gen.nextKey() + ", " + gen.nextKey();
            System.out.println(entry.getKey() + ": keys " + keys + " from " + gen.getClass().getSimpleName());
        }
    }
}
Output
test: keys 1, 2, 3 from CounterKeyGenerator
production: keys 1001, 1002, 1003 from SequenceKeyGenerator
broken: error: no plugin named FileKeyGenerator
  • Verdict: stdlib. Class.forName loads the class that the configuration names, and iface.cast checks that it implements the interface. java.util.ServiceLoader is the standard way to find providers that are deployed on the class path.
  • The binary name of a nested class has a $, such as Main$CounterKeyGenerator.
JavaScriptGitHub
class CounterKeyGenerator {
  // for unit tests: a counter in memory
  last = 0;
  nextKey() {
    return ++this.last;
  }
}

class SequenceKeyGenerator {
  // for production: it stands for a database sequence
  last = 1000;
  nextKey() {
    return ++this.last;
  }
}

// JavaScript cannot find a class by its name, so each plugin registers itself under a name.
// In a real program, the configuration can also name a module that import() loads.
const plugins = new Map();
plugins.set("CounterKeyGenerator", () => new CounterKeyGenerator());
plugins.set("SequenceKeyGenerator", () => new SequenceKeyGenerator());

// One configuration for each deployment. Only the configuration names the classes.
const CONFIGS = {
  test: { KeyGenerator: "CounterKeyGenerator" },
  production: { KeyGenerator: "SequenceKeyGenerator" },
  broken: { KeyGenerator: "FileKeyGenerator" },
};

class PluginFactory {
  constructor(config) {
    this.config = config;
  }

  get(iface) {
    const name = this.config[iface];
    const make = plugins.get(name);
    if (!make) throw new Error(`no plugin named ${name}`);
    return make();
  }
}

for (const [name, config] of Object.entries(CONFIGS)) {
  let gen;
  try {
    gen = new PluginFactory(config).get("KeyGenerator");
  } catch (e) {
    console.log(`${name}: error: ${e.message}`);
    continue;
  }
  const keys = [gen.nextKey(), gen.nextKey(), gen.nextKey()].join(", ");
  console.log(`${name}: keys ${keys} from ${gen.constructor.name}`);
}
Output
test: keys 1, 2, 3 from CounterKeyGenerator
production: keys 1001, 1002, 1003 from SequenceKeyGenerator
broken: error: no plugin named FileKeyGenerator
  • Verdict: idiom. JavaScript cannot create a class from a string name, so each plugin registers a constructor in a map. A configuration can also name a module path that a dynamic import() loads.
  • gen.constructor.name gives the name of the class of the loaded object.
package main

import (
	"fmt"
	"strings"
)

type KeyGenerator interface {
	NextKey() int64
}

// CounterKeyGenerator is for unit tests: a counter in memory.
type CounterKeyGenerator struct{ last int64 }

func (g *CounterKeyGenerator) NextKey() int64 { g.last++; return g.last }

// SequenceKeyGenerator is for production: it stands for a database sequence.
type SequenceKeyGenerator struct{ last int64 }

func (g *SequenceKeyGenerator) NextKey() int64 { g.last++; return g.last }

// Go cannot create a type from its name, so each plugin registers a constructor,
// as database drivers do with sql.Register.
var plugins = map[string]func() KeyGenerator{}

func Register(name string, make func() KeyGenerator) { plugins[name] = make }

func init() {
	Register("CounterKeyGenerator", func() KeyGenerator { return &CounterKeyGenerator{} })
	Register("SequenceKeyGenerator", func() KeyGenerator { return &SequenceKeyGenerator{last: 1000} })
}

type PluginFactory struct{ config map[string]string }

func (f PluginFactory) KeyGenerator() (KeyGenerator, string, error) {
	name := f.config["KeyGenerator"]
	make, ok := plugins[name]
	if !ok {
		return nil, "", fmt.Errorf("no plugin named %s", name)
	}
	return make(), name, nil
}

func main() {
	// One configuration for each deployment. Only the configuration names the types.
	names := []string{"test", "production", "broken"}
	configs := map[string]map[string]string{
		"test":       {"KeyGenerator": "CounterKeyGenerator"},
		"production": {"KeyGenerator": "SequenceKeyGenerator"},
		"broken":     {"KeyGenerator": "FileKeyGenerator"},
	}
	for _, name := range names {
		gen, plugin, err := PluginFactory{configs[name]}.KeyGenerator()
		if err != nil {
			fmt.Printf("%s: error: %v\n", name, err)
			continue
		}
		keys := make([]string, 3)
		for i := range keys {
			keys[i] = fmt.Sprint(gen.NextKey())
		}
		fmt.Printf("%s: keys %s from %s\n", name, strings.Join(keys, ", "), plugin)
	}
}
Output
test: keys 1, 2, 3 from CounterKeyGenerator
production: keys 1001, 1002, 1003 from SequenceKeyGenerator
broken: error: no plugin named FileKeyGenerator
  • Verdict: idiom. Go cannot create a type from its name, so each plugin registers a constructor in init, in the same way as database drivers call sql.Register. A program imports the package of a plugin only for this side effect.
  • The standard plugin package loads shared objects at run time, but its documentation warns that it works only on some platforms.
RustGitHub
use std::collections::HashMap;

trait KeyGenerator {
    fn next_key(&mut self) -> i64;
}

// For unit tests: a counter in memory.
struct CounterKeyGenerator {
    last: i64,
}

impl KeyGenerator for CounterKeyGenerator {
    fn next_key(&mut self) -> i64 {
        self.last += 1;
        self.last
    }
}

// For production: it stands for a database sequence.
struct SequenceKeyGenerator {
    last: i64,
}

impl KeyGenerator for SequenceKeyGenerator {
    fn next_key(&mut self) -> i64 {
        self.last += 1;
        self.last
    }
}

type Maker = fn() -> Box<dyn KeyGenerator>;

// Rust has no class loading by name, so the program keeps a table of named constructors.
fn plugins() -> HashMap<&'static str, Maker> {
    let mut m: HashMap<&'static str, Maker> = HashMap::new();
    m.insert("CounterKeyGenerator", || Box::new(CounterKeyGenerator { last: 0 }));
    m.insert("SequenceKeyGenerator", || Box::new(SequenceKeyGenerator { last: 1000 }));
    m
}

struct PluginFactory<'a> {
    config: HashMap<&'a str, &'a str>,
}

impl<'a> PluginFactory<'a> {
    fn get(&self, iface: &str) -> Result<(Box<dyn KeyGenerator>, &'a str), String> {
        let name = self.config[iface];
        match plugins().get(name) {
            Some(make) => Ok((make(), name)),
            None => Err(format!("no plugin named {}", name)),
        }
    }
}

fn main() {
    // One configuration for each deployment. Only the configuration names the types.
    let configs = [
        ("test", "CounterKeyGenerator"),
        ("production", "SequenceKeyGenerator"),
        ("broken", "FileKeyGenerator"),
    ];
    for (name, class) in configs {
        let factory = PluginFactory { config: HashMap::from([("KeyGenerator", class)]) };
        match factory.get("KeyGenerator") {
            Err(e) => println!("{}: error: {}", name, e),
            Ok((mut keygen, plugin)) => {
                let keys: Vec<String> = (0..3).map(|_| keygen.next_key().to_string()).collect();
                println!("{}: keys {} from {}", name, keys.join(", "), plugin);
            }
        }
    }
}
Output
test: keys 1, 2, 3 from CounterKeyGenerator
production: keys 1001, 1002, 1003 from SequenceKeyGenerator
broken: error: no plugin named FileKeyGenerator
  • Verdict: idiom. Rust has no class loading by name, so the program keeps a table of named constructors, and the configuration chooses one. Cargo features or a dynamic library are the other choices.
  • Maker is a function pointer type. Closures with no captures convert to it.

Consequences

Benefits.

  • One place for the configuration. A new deployment is a new configuration, with no change of the code.
  • No new build. The program chooses the implementation when it starts, so the same build runs in tests and in production.
  • New implementations from outside. A package that the program does not know when it is built can add an implementation, if the program loads it by name.

Liabilities.

Without a plugin, each factory has its own test of the mode, and they can disagree. In the following program, a new mode staging is added to one factory but not to the other. The staging program sends no real mail, but it uses the database sequence of production.

This code runs but gives a wrong answer on purpose.

MODE = "staging"  # a new deployment mode


def key_generator():  # one factory
    if MODE == "test":
        return "counter in memory"
    return "database sequence"


def mailer():  # another factory, in another module
    if MODE in ("test", "staging"):  # only this factory knows the new mode
        return "fake mailer"
    return "real mailer"


print(f"{MODE}: {key_generator()} + {mailer()}")
Output
staging: database sequence + fake mailer

Give each mode one configuration that names the implementation of each interface, and let one plugin factory read it.

Errors move to the start of the program. A wrong class name in the configuration is not found by the compiler. The factory must check the configuration when the program starts, and give an error that names the missing plugin.

Harder to follow. To know which class runs, a reader must look at the configuration and not at the code.

Loading code by name is a risk. If an attacker can change the configuration, the program loads the code that the attacker chooses. Keep the configuration as safe as the code.

When not to use it

When there is one implementation. A plugin factory and a configuration add work for nothing.

When the choice never changes after the build. If the build already knows the implementation, for example a library for one platform, a compile-time choice is simpler and the compiler checks it.

Service providers. Java has a standard plugin mechanism. "A service is a well-known interface or class for which zero, one, or many service providers exist."3 A JAR file names its providers in a provider-configuration file in the directory META-INF/services, and ServiceLoader loads them.3

Entry points. "Entry points are a mechanism for an installed distribution to advertise components it provides to be discovered and used by other code."2 The specification adds: "Applications can use entry points to load plugins".2

Registration by name. In Go, "Register makes a database driver available by the provided name."4 Each driver package registers itself, and the program chooses a driver by the name in its configuration.

Related patterns. Dependency injection containers often read the same kind of configuration and then give each object its dependencies. A Service locator or a Registry can keep the objects that the plugin factory creates. A plugin is a common way to choose a Service stub in tests in place of a Gateway to a real service. The book shows the pattern with a separated interface and a factory that reads a properties file.5

Known uses

  • Java ServiceLoader finds the providers of a service on the class path or the module path.3
  • Python tools such as Pygments load plugins from entry points of other installed packages.2
  • Go database drivers register themselves with sql.Register.4

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Plugin, pattern summary, by David Rice and Matt Foemmel
  2. Python Packaging User Guide, Entry points specification, Data model
  3. Java SE 21 API, java.util.ServiceLoader, class description, Deploying service providers on the class path
  4. Go standard library, database/sql, func Register
  5. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Plugin

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