Article · Abstract Factory · Factory Method
Abstract Factory – whole families of objects that fit together
Abstract Factory creates a complete set of related objects from one family and makes sure nobody mixes parts from different sets. An example with two payment provider integrations.
When an application uses several objects that must come "from the same set", individual new calls scattered around the code are asking for trouble. Abstract Factory is one object that produces a whole family of collaborating products – and guarantees they all belong to the same family.
The problem: payment from one provider, webhook from another
An online shop supports two payment providers: the international GlobalPay (cards) and the local Przelewik (instant bank transfers). Each provider has its own way of charging the customer and its own signature format for the notifications (webhooks) that confirm a payment. The code was written at different times by different people:
// checkout.ts
const charger = config.provider === "globalpay" ? new GlobalPayCharger() : new PrzelewikCharger();
// webhooks.ts – written by someone else, months later
const verifier = process.env.PSP === "przelewik" ? new PrzelewikVerifier() : new GlobalPayVerifier();Two sources of configuration, two conditions, zero guarantee of consistency. One typo in an environment variable and GlobalPay takes the money while Przelewik's module verifies the notifications – rejecting every single one as forged. Orders stay "unpaid" even though customers paid. On top of that, adding a third provider means hunting down every such condition across the repository.
The solution: one object for the whole family
We introduce a PaymentKit interface that can produce every product needed to handle payments. Each provider gets its own implementation – GlobalPayKit and PrzelewikKit. The Checkout class accepts a single kit and takes all objects from it, so mixing families becomes impossible by the very shape of the code.
A helpful picture: a family is a row, a kind of product is a column. A concrete factory is responsible for a whole row. A new family (say, a mobile payments provider) is a new row – you add one factory class and its products without touching the client. A new kind of product (say, refunds) is a new column – and that gets expensive, because the interface and every factory change.
| Family \ product | Charger | WebhookVerifier |
|---|---|---|
GlobalPayKit | ch_… | gp= signature |
PrzelewikKit | PRZ-…-PLN | prz= signature |
| new family | + 1 class | + 1 class |
| Role | In the example | Responsibility |
|---|---|---|
| Abstract factory | PaymentKit | declares methods that create each kind of product |
| Concrete factory | GlobalPayKit, PrzelewikKit | creates the products of one family |
| Abstract product | Charger, WebhookVerifier | interfaces the client works with |
| Concrete product | GlobalPayCharger, PrefixVerifier("gp=") | family-specific implementations |
| Client | Checkout | uses abstractions only; receives the factory from outside |
Implementation in five languages
We simplify signature verification to a prefix check – real providers use HMAC signatures, but that is not the point here. Look at the program's output: the Przelewik kit rejects a GlobalPay-style signature. That is exactly the mistake you can no longer make by mixing families accidentally.
IPaymentKit
foreach (IPaymentKit kit in new IPaymentKit[] { new GlobalPayKit(), new PrzelewikKit() })
{
var checkout = new Checkout(kit);
Console.WriteLine($"{checkout.Pay(4990)} | gp=abc valid: {checkout.OnWebhook("gp=abc")}");
}
public interface ICharger { string Charge(long amountCents); }
public interface IWebhookVerifier { bool Verify(string signature); }
// Abstract factory: one object, one consistent family of products.
public interface IPaymentKit
{
ICharger CreateCharger();
IWebhookVerifier CreateVerifier();
}
public sealed class GlobalPayKit : IPaymentKit
{
public ICharger CreateCharger() => new GlobalPayCharger();
public IWebhookVerifier CreateVerifier() => new PrefixVerifier("gp=");
}
public sealed class PrzelewikKit : IPaymentKit
{
public ICharger CreateCharger() => new PrzelewikCharger();
public IWebhookVerifier CreateVerifier() => new PrefixVerifier("prz=");
}
internal sealed class GlobalPayCharger : ICharger
{
public string Charge(long amountCents) => $"ch_{amountCents}";
}
internal sealed class PrzelewikCharger : ICharger
{
public string Charge(long amountCents) => $"PRZ-{amountCents}-PLN";
}
// Real providers verify HMAC signatures; a prefix check keeps the example short.
internal sealed record PrefixVerifier(string Prefix) : IWebhookVerifier
{
public bool Verify(string signature) => signature.StartsWith(Prefix, StringComparison.Ordinal);
}
// The client sees only abstractions; both products come from the same kit, so they always match.
public sealed class Checkout(IPaymentKit kit)
{
private readonly ICharger _charger = kit.CreateCharger();
private readonly IWebhookVerifier _verifier = kit.CreateVerifier();
public string Pay(long amountCents) => _charger.Charge(amountCents);
public bool OnWebhook(string signature) => _verifier.Verify(signature);
}interface Charger {
charge(amountCents: number): string;
}
interface WebhookVerifier {
verify(signature: string): boolean;
}
// Abstract factory: one object, one consistent family of products.
interface PaymentKit {
createCharger(): Charger;
createVerifier(): WebhookVerifier;
}
// Real providers verify HMAC signatures; a prefix check keeps the example short.
const globalPay: PaymentKit = {
createCharger: () => ({ charge: (cents) => `ch_${cents}` }),
createVerifier: () => ({ verify: (sig) => sig.startsWith("gp=") }),
};
const przelewik: PaymentKit = {
createCharger: () => ({ charge: (cents) => `PRZ-${cents}-PLN` }),
createVerifier: () => ({ verify: (sig) => sig.startsWith("prz=") }),
};
class Checkout {
private readonly charger: Charger;
private readonly verifier: WebhookVerifier;
constructor(kit: PaymentKit) {
// Both products come from the same kit, so they always match.
this.charger = kit.createCharger();
this.verifier = kit.createVerifier();
}
pay(amountCents: number): string {
return this.charger.charge(amountCents);
}
onWebhook(signature: string): boolean {
return this.verifier.verify(signature);
}
}
for (const kit of [globalPay, przelewik]) {
const checkout = new Checkout(kit);
console.log(checkout.pay(4990), "| gp=abc valid:", checkout.onWebhook("gp=abc"));
}import java.util.List;
interface Charger { String charge(long amountCents); }
interface WebhookVerifier { boolean verify(String signature); }
// Abstract factory: one object, one consistent family of products.
interface PaymentKit {
Charger createCharger();
WebhookVerifier createVerifier();
}
// Real providers verify HMAC signatures; a prefix check keeps the example short.
final class GlobalPayKit implements PaymentKit {
public Charger createCharger() { return cents -> "ch_" + cents; }
public WebhookVerifier createVerifier() { return sig -> sig.startsWith("gp="); }
}
final class PrzelewikKit implements PaymentKit {
public Charger createCharger() { return cents -> "PRZ-" + cents + "-PLN"; }
public WebhookVerifier createVerifier() { return sig -> sig.startsWith("prz="); }
}
final class Checkout {
private final Charger charger;
private final WebhookVerifier verifier;
Checkout(PaymentKit kit) {
// Both products come from the same kit, so they always match.
this.charger = kit.createCharger();
this.verifier = kit.createVerifier();
}
String pay(long amountCents) { return charger.charge(amountCents); }
boolean onWebhook(String signature) { return verifier.verify(signature); }
}
public class Payments {
public static void main(String[] args) {
List<PaymentKit> kits = List.of(new GlobalPayKit(), new PrzelewikKit());
for (PaymentKit kit : kits) {
Checkout checkout = new Checkout(kit);
System.out.println(checkout.pay(4990) + " | gp=abc valid: " + checkout.onWebhook("gp=abc"));
}
}
}package main
import (
"fmt"
"strings"
)
type Charger interface{ Charge(amountCents int64) string }
type WebhookVerifier interface{ Verify(signature string) bool }
// PaymentKit is the abstract factory: one value, one consistent family of products.
type PaymentKit interface {
NewCharger() Charger
NewVerifier() WebhookVerifier
}
// Real providers verify HMAC signatures; a prefix check keeps the example short.
type prefixVerifier struct{ prefix string }
func (v prefixVerifier) Verify(sig string) bool { return strings.HasPrefix(sig, v.prefix) }
type globalPayCharger struct{}
func (globalPayCharger) Charge(c int64) string { return fmt.Sprintf("ch_%d", c) }
type GlobalPayKit struct{}
func (GlobalPayKit) NewCharger() Charger { return globalPayCharger{} }
func (GlobalPayKit) NewVerifier() WebhookVerifier { return prefixVerifier{"gp="} }
type przelewikCharger struct{}
func (przelewikCharger) Charge(c int64) string { return fmt.Sprintf("PRZ-%d-PLN", c) }
type PrzelewikKit struct{}
func (PrzelewikKit) NewCharger() Charger { return przelewikCharger{} }
func (PrzelewikKit) NewVerifier() WebhookVerifier { return prefixVerifier{"prz="} }
type Checkout struct {
charger Charger
verifier WebhookVerifier
}
// NewCheckout takes both products from the same kit, so they always match.
func NewCheckout(kit PaymentKit) Checkout {
return Checkout{charger: kit.NewCharger(), verifier: kit.NewVerifier()}
}
func main() {
for _, kit := range []PaymentKit{GlobalPayKit{}, PrzelewikKit{}} {
c := NewCheckout(kit)
fmt.Println(c.charger.Charge(4990), "| gp=abc valid:", c.verifier.Verify("gp=abc"))
}
}from dataclasses import dataclass
from typing import Protocol
class Charger(Protocol):
def charge(self, amount_cents: int) -> str: ...
class WebhookVerifier(Protocol):
def verify(self, signature: str) -> bool: ...
class PaymentKit(Protocol):
"""Abstract factory: one object, one consistent family of products."""
def create_charger(self) -> Charger: ...
def create_verifier(self) -> WebhookVerifier: ...
@dataclass(frozen=True)
class PrefixVerifier: # real providers check HMAC signatures
prefix: str
def verify(self, signature: str) -> bool:
return signature.startswith(self.prefix)
@dataclass(frozen=True)
class TemplateCharger: # each provider formats payment ids its own way
template: str
def charge(self, amount_cents: int) -> str:
return self.template.format(amount_cents)
class GlobalPayKit:
def create_charger(self) -> Charger:
return TemplateCharger("ch_{}")
def create_verifier(self) -> WebhookVerifier:
return PrefixVerifier("gp=")
class PrzelewikKit:
def create_charger(self) -> Charger:
return TemplateCharger("PRZ-{}-PLN")
def create_verifier(self) -> WebhookVerifier:
return PrefixVerifier("prz=")
class Checkout:
def __init__(self, kit: PaymentKit) -> None:
# Both products come from the same kit, so they always match.
self.charger = kit.create_charger()
self.verifier = kit.create_verifier()
if __name__ == "__main__":
for kit in (GlobalPayKit(), PrzelewikKit()):
checkout = Checkout(kit)
print(checkout.charger.charge(4990), "| gp=abc valid:", checkout.verifier.verify("gp=abc"))The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step by step
- When to use it and when not to
- Related patterns
- In practice
- Quick check
- Summary