Abstract Factory: Parts That Must Match
When each brand needs its own connection, command format and status reader, and three separate factories each pick one by the brand's name, one copied line can hand a Bolt lock a Tuneo reader; an abstract factory gives each brand one kit that makes all of its parts, so they can't be mixed.
Journeyman · OOP · Updated
After this lesson you can
- Give each family of parts that must match one factory, so code can't mix one family's parts with another's
- Spot the smells that point to Abstract Factory: several choices on the same name that must always agree
Key takeaways
- The smell: several if-chains (or factories) on the same name, which must always agree, and nothing that makes them agree.
- The cause: the parts belong together as a family, but each one is picked on its own.
- The fix: one factory per family (a kit) that makes every part of it. Code asks one kit for all its parts, so it can't mix two brands.
- Adding a family is one new kit. Adding a new kind of part means changing every kit, so use it when the kinds of parts are settled.
Before this: Simple Factory: One Place That Says new, and Meet the Smart-Home Hub. This lesson uses interfaces throughout.
The adapters fixed how the hub's routines call a device. Underneath, there's a second job: getting a command to the device at all. Each brand's devices are reached through that brand's own box on the home network, its bridge, and every brand talks to its bridge differently. Lumo's bridge reads JSON ({"power": true}), Bolt's reads short codes (B:1), and Tuneo's reads key=value pairs (cmd=play). By the end of this lesson you'll have met a pattern for parts that have to match, called Abstract Factory.
Each brand needs three parts, and they must match
To send one command, the hub needs three parts from the same brand:
- a connection to that brand's bridge, which sends a message and hands back the reply;
- a command format, which turns the hub's command (
"on","lock","play") into the brand's message; - a status reader, which turns the brand's reply (
ENGAGED,state=playing) into the hub's word ("locked","playing").
A Bolt bridge can't read JSON, and a Tuneo reader can't read ENGAGED. Mix two brands' parts and the command fails.

The symptom: three factories that have to agree
The team already knew one cure from Pass 1, the simple factory, so they wrote three: one picks the connection, one the format, one the reader, each by the brand's name. Each one works on its own. Read the third one closely:
Send("lumo", "kitchen light", "on");
Send("bolt", "front door", "lock");
Send("tuneo", "kitchen speaker", "play");
void Send(string brand, string device, string command)
{
string reply = ConnectionFor(brand).Send(FormatFor(brand).Encode(command));
Console.WriteLine( quot;{device}: {ReaderFor(brand).Read(reply)}");
}
IConnection ConnectionFor(string brand)
{
if (brand == "lumo") return new LumoConnection();
if (brand == "bolt") return new BoltConnection();
return new TuneoConnection();
}
ICommandFormat FormatFor(string brand)
{
if (brand == "lumo") return new LumoFormat();
if (brand == "bolt") return new BoltFormat();
return new TuneoFormat();
}
IStatusReader ReaderFor(string brand)
{
if (brand == "lumo") return new LumoReader();
if (brand == "bolt") return new TuneoReader();
return new TuneoReader();
}
interface IConnection { string Send(string message); }
interface ICommandFormat { string Encode(string command); }
interface IStatusReader { string Read(string reply); }
class LumoConnection : IConnection { public string Send(string message) => message.StartsWith("{") ? message : "error"; }
class LumoFormat : ICommandFormat { public string Encode(string command) => command == "on" ? "{\"power\": true}" : "{\"power\": false}"; }
class LumoReader : IStatusReader { public string Read(string reply) => reply == "{\"power\": true}" ? "on" : reply == "{\"power\": false}" ? "off" : "error"; }
class BoltConnection : IConnection { public string Send(string message) => message == "B:1" ? "ENGAGED" : message == "B:0" ? "RELEASED" : "error"; }
class BoltFormat : ICommandFormat { public string Encode(string command) => command == "lock" ? "B:1" : "B:0"; }
class BoltReader : IStatusReader { public string Read(string reply) => reply == "ENGAGED" ? "locked" : reply == "RELEASED" ? "unlocked" : "error"; }
class TuneoConnection : IConnection { public string Send(string message) => message == "cmd=play" ? "state=playing" : message == "cmd=stop" ? "state=stopped" : "error"; }
class TuneoFormat : ICommandFormat { public string Encode(string command) => "cmd=" + command; }
class TuneoReader : IStatusReader { public string Read(string reply) => reply.StartsWith("state=") ? reply.Substring(6) : "error"; }
kitchen light: on
front door: error
kitchen speaker: playing
interface Connection { String send(String message); }
interface CommandFormat { String encode(String command); }
interface StatusReader { String read(String reply); }
class LumoConnection implements Connection { public String send(String message) { return message.startsWith("{") ? message : "error"; } }
class LumoFormat implements CommandFormat { public String encode(String command) { return command.equals("on") ? "{\"power\": true}" : "{\"power\": false}"; } }
class LumoReader implements StatusReader { public String read(String reply) { return reply.equals("{\"power\": true}") ? "on" : reply.equals("{\"power\": false}") ? "off" : "error"; } }
class BoltConnection implements Connection { public String send(String message) { return message.equals("B:1") ? "ENGAGED" : message.equals("B:0") ? "RELEASED" : "error"; } }
class BoltFormat implements CommandFormat { public String encode(String command) { return command.equals("lock") ? "B:1" : "B:0"; } }
class BoltReader implements StatusReader { public String read(String reply) { return reply.equals("ENGAGED") ? "locked" : reply.equals("RELEASED") ? "unlocked" : "error"; } }
class TuneoConnection implements Connection { public String send(String message) { return message.equals("cmd=play") ? "state=playing" : message.equals("cmd=stop") ? "state=stopped" : "error"; } }
class TuneoFormat implements CommandFormat { public String encode(String command) { return "cmd=" + command; } }
class TuneoReader implements StatusReader { public String read(String reply) { return reply.startsWith("state=") ? reply.substring(6) : "error"; } }
Connection connectionFor(String brand) {
if (brand.equals("lumo")) return new LumoConnection();
if (brand.equals("bolt")) return new BoltConnection();
return new TuneoConnection();
}
CommandFormat formatFor(String brand) {
if (brand.equals("lumo")) return new LumoFormat();
if (brand.equals("bolt")) return new BoltFormat();
return new TuneoFormat();
}
StatusReader readerFor(String brand) {
if (brand.equals("lumo")) return new LumoReader();
if (brand.equals("bolt")) return new TuneoReader();
return new TuneoReader();
}
void send(String brand, String device, String command) {
String reply = connectionFor(brand).send(formatFor(brand).encode(command));
IO.println(device + ": " + readerFor(brand).read(reply));
}
void main() {
send("lumo", "kitchen light", "on");
send("bolt", "front door", "lock");
send("tuneo", "kitchen speaker", "play");
}
kitchen light: on
front door: error
kitchen speaker: playing
class LumoConnection:
def send(self, message): return message if message.startswith("{") else "error"
class LumoFormat:
def encode(self, command): return '{"power": true}' if command == "on" else '{"power": false}'
class LumoReader:
def read(self, reply): return {'{"power": true}': "on", '{"power": false}': "off"}.get(reply, "error")
class BoltConnection:
def send(self, message): return {"B:1": "ENGAGED", "B:0": "RELEASED"}.get(message, "error")
class BoltFormat:
def encode(self, command): return "B:1" if command == "lock" else "B:0"
class BoltReader:
def read(self, reply): return {"ENGAGED": "locked", "RELEASED": "unlocked"}.get(reply, "error")
class TuneoConnection:
def send(self, message): return {"cmd=play": "state=playing", "cmd=stop": "state=stopped"}.get(message, "error")
class TuneoFormat:
def encode(self, command): return "cmd=" + command
class TuneoReader:
def read(self, reply): return reply[6:] if reply.startswith("state=") else "error"
def connection_for(brand):
if brand == "lumo":
return LumoConnection()
if brand == "bolt":
return BoltConnection()
return TuneoConnection()
def format_for(brand):
if brand == "lumo":
return LumoFormat()
if brand == "bolt":
return BoltFormat()
return TuneoFormat()
def reader_for(brand):
if brand == "lumo":
return LumoReader()
if brand == "bolt":
return TuneoReader()
return TuneoReader()
def send(brand, device, command):
reply = connection_for(brand).send(format_for(brand).encode(command))
print(f"{device}: {reader_for(brand).read(reply)}")
send("lumo", "kitchen light", "on")
send("bolt", "front door", "lock")
send("tuneo", "kitchen speaker", "play")
kitchen light: on
front door: error
kitchen speaker: playing
class LumoConnection { send(message) { return message.startsWith("{") ? message : "error"; } }
class LumoFormat { encode(command) { return command === "on" ? '{"power": true}' : '{"power": false}'; } }
class LumoReader { read(reply) { return reply === '{"power": true}' ? "on" : reply === '{"power": false}' ? "off" : "error"; } }
class BoltConnection { send(message) { return message === "B:1" ? "ENGAGED" : message === "B:0" ? "RELEASED" : "error"; } }
class BoltFormat { encode(command) { return command === "lock" ? "B:1" : "B:0"; } }
class BoltReader { read(reply) { return reply === "ENGAGED" ? "locked" : reply === "RELEASED" ? "unlocked" : "error"; } }
class TuneoConnection { send(message) { return message === "cmd=play" ? "state=playing" : message === "cmd=stop" ? "state=stopped" : "error"; } }
class TuneoFormat { encode(command) { return "cmd=" + command; } }
class TuneoReader { read(reply) { return reply.startsWith("state=") ? reply.slice(6) : "error"; } }
function connectionFor(brand) {
if (brand === "lumo") return new LumoConnection();
if (brand === "bolt") return new BoltConnection();
return new TuneoConnection();
}
function formatFor(brand) {
if (brand === "lumo") return new LumoFormat();
if (brand === "bolt") return new BoltFormat();
return new TuneoFormat();
}
function readerFor(brand) {
if (brand === "lumo") return new LumoReader();
if (brand === "bolt") return new TuneoReader();
return new TuneoReader();
}
function send(brand, device, command) {
const reply = connectionFor(brand).send(formatFor(brand).encode(command));
console.log(`${device}: ${readerFor(brand).read(reply)}`);
}
send("lumo", "kitchen light", "on");
send("bolt", "front door", "lock");
send("tuneo", "kitchen speaker", "play");
kitchen light: on
front door: error
kitchen speaker: playing
interface Connection { send(message: string): string; }
interface CommandFormat { encode(command: string): string; }
interface StatusReader { read(reply: string): string; }
class LumoConnection implements Connection { send(message: string): string { return message.startsWith("{") ? message : "error"; } }
class LumoFormat implements CommandFormat { encode(command: string): string { return command === "on" ? '{"power": true}' : '{"power": false}'; } }
class LumoReader implements StatusReader { read(reply: string): string { return reply === '{"power": true}' ? "on" : reply === '{"power": false}' ? "off" : "error"; } }
class BoltConnection implements Connection { send(message: string): string { return message === "B:1" ? "ENGAGED" : message === "B:0" ? "RELEASED" : "error"; } }
class BoltFormat implements CommandFormat { encode(command: string): string { return command === "lock" ? "B:1" : "B:0"; } }
class BoltReader implements StatusReader { read(reply: string): string { return reply === "ENGAGED" ? "locked" : reply === "RELEASED" ? "unlocked" : "error"; } }
class TuneoConnection implements Connection { send(message: string): string { return message === "cmd=play" ? "state=playing" : message === "cmd=stop" ? "state=stopped" : "error"; } }
class TuneoFormat implements CommandFormat { encode(command: string): string { return "cmd=" + command; } }
class TuneoReader implements StatusReader { read(reply: string): string { return reply.startsWith("state=") ? reply.slice(6) : "error"; } }
function connectionFor(brand: string): Connection {
if (brand === "lumo") return new LumoConnection();
if (brand === "bolt") return new BoltConnection();
return new TuneoConnection();
}
function formatFor(brand: string): CommandFormat {
if (brand === "lumo") return new LumoFormat();
if (brand === "bolt") return new BoltFormat();
return new TuneoFormat();
}
function readerFor(brand: string): StatusReader {
if (brand === "lumo") return new LumoReader();
if (brand === "bolt") return new TuneoReader();
return new TuneoReader();
}
function send(brand: string, device: string, command: string): void {
const reply = connectionFor(brand).send(formatFor(brand).encode(command));
console.log(`${device}: ${readerFor(brand).read(reply)}`);
}
send("lumo", "kitchen light", "on");
send("bolt", "front door", "lock");
send("tuneo", "kitchen speaker", "play");
kitchen light: on
front door: error
kitchen speaker: playing
The front door locked fine: the Bolt bridge got B:1 and answered ENGAGED. But the screen says error, because readerFor hands a Bolt reply to Tuneo's reader. Someone copied the last line up one and changed the wrong word. Each factory is correct about its own part; nothing makes the three of them agree.
- The symptom: several
ifchains (or factories) on the same name, which must always pick from the same brand, and nothing that makes them. - The cause: the parts are a family (a Lumo connection, a Lumo format and a Lumo reader belong together), but each one is picked on its own. A fourth brand means editing three chains and getting all three right.
What would you try?
Be more careful, and add a test for each brand. Tests would have caught this one. But the cause is still there: every new brand and every new part is another chance to pick one wrong, in three places.
Put all three choices in one function, with one if per brand that picks all three parts. Now they're picked together, which is the right idea. But it hands back three things at once from one growing if chain, and code that only needs a reader still runs the whole chain.
One class per brand that does all three jobs itself: connects, formats and reads. The parts can't be mixed now. But one class does three jobs, and when Tuneo's bridge changes how it connects, the class with Tuneo's reading in it changes too.
What we want is one place per brand that makes that brand's parts, each still its own small class, so asking for "Bolt's parts" can only ever hand back Bolt's.
The fix: one kit per brand
A party store sells themed kits. Pick the pirate kit, and its plates, cups and napkins all match; pick the space kit, and all of those are space. You choose the theme once, and you can't end up with pirate plates and space napkins, because nobody picks them one at a time.

In code, the kit is an abstract factory: an interface with one method for each part (connection(), format(), reader()), and one class per brand that keeps it by making that brand's parts. The code that sends a command is handed one kit, and asks it for everything:

Dictionary<string, IBrandKit> kits = new Dictionary<string, IBrandKit>
{
["lumo"] = new LumoKit(),
["bolt"] = new BoltKit(),
["tuneo"] = new TuneoKit(),
};
Send(kits["lumo"], "kitchen light", "on");
Send(kits["bolt"], "front door", "lock");
Send(kits["tuneo"], "kitchen speaker", "play");
// Every part comes from the one kit, so they always match.
void Send(IBrandKit kit, string device, string command)
{
string reply = kit.Connection().Send(kit.Format().Encode(command));
Console.WriteLine( quot;{device}: {kit.Reader().Read(reply)}");
}
// The kit: one method for each part of a brand's family.
interface IBrandKit
{
IConnection Connection();
ICommandFormat Format();
IStatusReader Reader();
}
class LumoKit : IBrandKit
{
public IConnection Connection() => new LumoConnection();
public ICommandFormat Format() => new LumoFormat();
public IStatusReader Reader() => new LumoReader();
}
class BoltKit : IBrandKit
{
public IConnection Connection() => new BoltConnection();
public ICommandFormat Format() => new BoltFormat();
public IStatusReader Reader() => new BoltReader();
}
class TuneoKit : IBrandKit
{
public IConnection Connection() => new TuneoConnection();
public ICommandFormat Format() => new TuneoFormat();
public IStatusReader Reader() => new TuneoReader();
}
interface IConnection { string Send(string message); }
interface ICommandFormat { string Encode(string command); }
interface IStatusReader { string Read(string reply); }
class LumoConnection : IConnection { public string Send(string message) => message.StartsWith("{") ? message : "error"; }
class LumoFormat : ICommandFormat { public string Encode(string command) => command == "on" ? "{\"power\": true}" : "{\"power\": false}"; }
class LumoReader : IStatusReader { public string Read(string reply) => reply == "{\"power\": true}" ? "on" : reply == "{\"power\": false}" ? "off" : "error"; }
class BoltConnection : IConnection { public string Send(string message) => message == "B:1" ? "ENGAGED" : message == "B:0" ? "RELEASED" : "error"; }
class BoltFormat : ICommandFormat { public string Encode(string command) => command == "lock" ? "B:1" : "B:0"; }
class BoltReader : IStatusReader { public string Read(string reply) => reply == "ENGAGED" ? "locked" : reply == "RELEASED" ? "unlocked" : "error"; }
class TuneoConnection : IConnection { public string Send(string message) => message == "cmd=play" ? "state=playing" : message == "cmd=stop" ? "state=stopped" : "error"; }
class TuneoFormat : ICommandFormat { public string Encode(string command) => "cmd=" + command; }
class TuneoReader : IStatusReader { public string Read(string reply) => reply.StartsWith("state=") ? reply.Substring(6) : "error"; }
kitchen light: on
front door: locked
kitchen speaker: playing
interface Connection { String send(String message); }
interface CommandFormat { String encode(String command); }
interface StatusReader { String read(String reply); }
class LumoConnection implements Connection { public String send(String message) { return message.startsWith("{") ? message : "error"; } }
class LumoFormat implements CommandFormat { public String encode(String command) { return command.equals("on") ? "{\"power\": true}" : "{\"power\": false}"; } }
class LumoReader implements StatusReader { public String read(String reply) { return reply.equals("{\"power\": true}") ? "on" : reply.equals("{\"power\": false}") ? "off" : "error"; } }
class BoltConnection implements Connection { public String send(String message) { return message.equals("B:1") ? "ENGAGED" : message.equals("B:0") ? "RELEASED" : "error"; } }
class BoltFormat implements CommandFormat { public String encode(String command) { return command.equals("lock") ? "B:1" : "B:0"; } }
class BoltReader implements StatusReader { public String read(String reply) { return reply.equals("ENGAGED") ? "locked" : reply.equals("RELEASED") ? "unlocked" : "error"; } }
class TuneoConnection implements Connection { public String send(String message) { return message.equals("cmd=play") ? "state=playing" : message.equals("cmd=stop") ? "state=stopped" : "error"; } }
class TuneoFormat implements CommandFormat { public String encode(String command) { return "cmd=" + command; } }
class TuneoReader implements StatusReader { public String read(String reply) { return reply.startsWith("state=") ? reply.substring(6) : "error"; } }
// The kit: one method for each part of a brand's family.
interface BrandKit {
Connection connection();
CommandFormat format();
StatusReader reader();
}
class LumoKit implements BrandKit {
public Connection connection() { return new LumoConnection(); }
public CommandFormat format() { return new LumoFormat(); }
public StatusReader reader() { return new LumoReader(); }
}
class BoltKit implements BrandKit {
public Connection connection() { return new BoltConnection(); }
public CommandFormat format() { return new BoltFormat(); }
public StatusReader reader() { return new BoltReader(); }
}
class TuneoKit implements BrandKit {
public Connection connection() { return new TuneoConnection(); }
public CommandFormat format() { return new TuneoFormat(); }
public StatusReader reader() { return new TuneoReader(); }
}
// Every part comes from the one kit, so they always match.
void send(BrandKit kit, String device, String command) {
String reply = kit.connection().send(kit.format().encode(command));
IO.println(device + ": " + kit.reader().read(reply));
}
void main() {
Map<String, BrandKit> kits = Map.of("lumo", new LumoKit(), "bolt", new BoltKit(), "tuneo", new TuneoKit());
send(kits.get("lumo"), "kitchen light", "on");
send(kits.get("bolt"), "front door", "lock");
send(kits.get("tuneo"), "kitchen speaker", "play");
}
kitchen light: on
front door: locked
kitchen speaker: playing
class LumoConnection:
def send(self, message): return message if message.startswith("{") else "error"
class LumoFormat:
def encode(self, command): return '{"power": true}' if command == "on" else '{"power": false}'
class LumoReader:
def read(self, reply): return {'{"power": true}': "on", '{"power": false}': "off"}.get(reply, "error")
class BoltConnection:
def send(self, message): return {"B:1": "ENGAGED", "B:0": "RELEASED"}.get(message, "error")
class BoltFormat:
def encode(self, command): return "B:1" if command == "lock" else "B:0"
class BoltReader:
def read(self, reply): return {"ENGAGED": "locked", "RELEASED": "unlocked"}.get(reply, "error")
class TuneoConnection:
def send(self, message): return {"cmd=play": "state=playing", "cmd=stop": "state=stopped"}.get(message, "error")
class TuneoFormat:
def encode(self, command): return "cmd=" + command
class TuneoReader:
def read(self, reply): return reply[6:] if reply.startswith("state=") else "error"
# The kits: one class per brand, with one method for each part of its family.
class LumoKit:
def connection(self): return LumoConnection()
def format(self): return LumoFormat()
def reader(self): return LumoReader()
class BoltKit:
def connection(self): return BoltConnection()
def format(self): return BoltFormat()
def reader(self): return BoltReader()
class TuneoKit:
def connection(self): return TuneoConnection()
def format(self): return TuneoFormat()
def reader(self): return TuneoReader()
def send(kit, device, command):
"""Every part comes from the one kit, so they always match."""
reply = kit.connection().send(kit.format().encode(command))
print(f"{device}: {kit.reader().read(reply)}")
kits = {"lumo": LumoKit(), "bolt": BoltKit(), "tuneo": TuneoKit()}
send(kits["lumo"], "kitchen light", "on")
send(kits["bolt"], "front door", "lock")
send(kits["tuneo"], "kitchen speaker", "play")
kitchen light: on
front door: locked
kitchen speaker: playing
class LumoConnection { send(message) { return message.startsWith("{") ? message : "error"; } }
class LumoFormat { encode(command) { return command === "on" ? '{"power": true}' : '{"power": false}'; } }
class LumoReader { read(reply) { return reply === '{"power": true}' ? "on" : reply === '{"power": false}' ? "off" : "error"; } }
class BoltConnection { send(message) { return message === "B:1" ? "ENGAGED" : message === "B:0" ? "RELEASED" : "error"; } }
class BoltFormat { encode(command) { return command === "lock" ? "B:1" : "B:0"; } }
class BoltReader { read(reply) { return reply === "ENGAGED" ? "locked" : reply === "RELEASED" ? "unlocked" : "error"; } }
class TuneoConnection { send(message) { return message === "cmd=play" ? "state=playing" : message === "cmd=stop" ? "state=stopped" : "error"; } }
class TuneoFormat { encode(command) { return "cmd=" + command; } }
class TuneoReader { read(reply) { return reply.startsWith("state=") ? reply.slice(6) : "error"; } }
// The kits: one class per brand, with one method for each part of its family.
class LumoKit {
connection() { return new LumoConnection(); }
format() { return new LumoFormat(); }
reader() { return new LumoReader(); }
}
class BoltKit {
connection() { return new BoltConnection(); }
format() { return new BoltFormat(); }
reader() { return new BoltReader(); }
}
class TuneoKit {
connection() { return new TuneoConnection(); }
format() { return new TuneoFormat(); }
reader() { return new TuneoReader(); }
}
// Every part comes from the one kit, so they always match.
function send(kit, device, command) {
const reply = kit.connection().send(kit.format().encode(command));
console.log(`${device}: ${kit.reader().read(reply)}`);
}
const kits = { lumo: new LumoKit(), bolt: new BoltKit(), tuneo: new TuneoKit() };
send(kits.lumo, "kitchen light", "on");
send(kits.bolt, "front door", "lock");
send(kits.tuneo, "kitchen speaker", "play");
kitchen light: on
front door: locked
kitchen speaker: playing
interface Connection { send(message: string): string; }
interface CommandFormat { encode(command: string): string; }
interface StatusReader { read(reply: string): string; }
class LumoConnection implements Connection { send(message: string): string { return message.startsWith("{") ? message : "error"; } }
class LumoFormat implements CommandFormat { encode(command: string): string { return command === "on" ? '{"power": true}' : '{"power": false}'; } }
class LumoReader implements StatusReader { read(reply: string): string { return reply === '{"power": true}' ? "on" : reply === '{"power": false}' ? "off" : "error"; } }
class BoltConnection implements Connection { send(message: string): string { return message === "B:1" ? "ENGAGED" : message === "B:0" ? "RELEASED" : "error"; } }
class BoltFormat implements CommandFormat { encode(command: string): string { return command === "lock" ? "B:1" : "B:0"; } }
class BoltReader implements StatusReader { read(reply: string): string { return reply === "ENGAGED" ? "locked" : reply === "RELEASED" ? "unlocked" : "error"; } }
class TuneoConnection implements Connection { send(message: string): string { return message === "cmd=play" ? "state=playing" : message === "cmd=stop" ? "state=stopped" : "error"; } }
class TuneoFormat implements CommandFormat { encode(command: string): string { return "cmd=" + command; } }
class TuneoReader implements StatusReader { read(reply: string): string { return reply.startsWith("state=") ? reply.slice(6) : "error"; } }
// The kit: one method for each part of a brand's family.
interface BrandKit {
connection(): Connection;
format(): CommandFormat;
reader(): StatusReader;
}
class LumoKit implements BrandKit {
connection(): Connection { return new LumoConnection(); }
format(): CommandFormat { return new LumoFormat(); }
reader(): StatusReader { return new LumoReader(); }
}
class BoltKit implements BrandKit {
connection(): Connection { return new BoltConnection(); }
format(): CommandFormat { return new BoltFormat(); }
reader(): StatusReader { return new BoltReader(); }
}
class TuneoKit implements BrandKit {
connection(): Connection { return new TuneoConnection(); }
format(): CommandFormat { return new TuneoFormat(); }
reader(): StatusReader { return new TuneoReader(); }
}
// Every part comes from the one kit, so they always match.
function send(kit: BrandKit, device: string, command: string): void {
const reply = kit.connection().send(kit.format().encode(command));
console.log(`${device}: ${kit.reader().read(reply)}`);
}
const kits: Record<string, BrandKit> = { lumo: new LumoKit(), bolt: new BoltKit(), tuneo: new TuneoKit() };
send(kits["lumo"], "kitchen light", "on");
send(kits["bolt"], "front door", "lock");
send(kits["tuneo"], "kitchen speaker", "play");
kitchen light: on
front door: locked
kitchen speaker: playing
The front door reads locked now. send never picks a part: it's handed one kit and asks it for all three, so a Bolt reply can only ever reach Bolt's reader. The brand is chosen once, in one place (the kits dictionary, Pass 1's dictionary of functions idea holding kits).
A fourth brand is one new kit and its three small parts, plus one line in kits. Nothing in send changes, and there's no chain left to copy a wrong line into.
Where the languages differ. In C#, Java and TypeScript the BrandKit interface makes the compiler check that every kit makes all three parts. In Python and JavaScript, any object with connection(), format() and reader() methods is a kit. Python and JavaScript code often skips the kit classes and uses a plain object or module per brand that holds the three parts; it's the same pattern.
How it got its name
The fix kept turning up wherever families of parts had to match: database libraries, where a connection and its commands must come from the same database maker, and screen toolkits, where a theme's buttons, menus and scroll bars must match. It's in the original 1994 book as the Abstract Factory (also called a Kit). It's a factory because it makes things, and abstract because the code that uses it only knows the interface, BrandKit, never which brand's kit it holds. Each of a kit's methods is a small factory method.
Compared with Pass 1's simple factory: a simple factory makes one kind of thing, and picks which class by a name. An abstract factory makes a set of things that belong together, and you pick the whole set at once by picking the kit.
Where you've already used it
- .NET's
DbProviderFactorymakes a connection, a command and a parameter for one database maker, all matching:CreateConnection(),CreateCommand(),CreateParameter(). - A database driver in Java (JDBC) works the same way: a driver's
Connectionmakes theStatementobjects that go with it, never another maker's. - A screen toolkit's themes (a light theme and a dark theme) each make buttons, text boxes and menus that match.
When not to use it
- When there's one kind of part. If each brand only needed a reader, a simple factory or a dictionary of functions does the job with less code.
- When the parts don't have to match. If any reader works with any connection, picking them separately is fine, and simpler.
- When the kinds of parts keep changing. Adding a brand is cheap: one new kit. Adding a fourth kind of part (say, a firmware updater) means changing the
BrandKitinterface and every kit. Use it once the parts are settled.
The cost is one more interface and one class per family, on top of the parts themselves.
How often you'll meet it: now and then (our estimate: you'll use abstract factories inside libraries and frameworks far more often than you'll write one).
Check yourself
2 questions to try on the lesson page.
So what
When parts belong together and mixing them breaks things, don't pick them one at a time. Pick the family once, as a kit, and let the kit hand out every part.