---
title: "Factory pattern"
date: "2026-03"
category: "Design Patterns & Architecture"
tags: ["Design Patterns & Architecture"]
description: "This one is kind of interesting. It's essentially another use of higher-order functions: you expose your public interface as taking a key and a func\\<key,V>..."
source: "https://enriquemark.com/en/posts/%E5%B7%A5%E5%BB%A0%E6%A8%A1%E5%BC%8F"
---

This one is kind of interesting. It's essentially another use of higher-order functions: you expose your public interface as taking a key and a func\<key,V>. The key here is the element of the current func, and V is the output type under the C# type declaration. The factory does its work based on what gets passed in, and this way of not running it yourself but handing the function to the factory to run is called a delegate. Also literally what it says. I'm not doing it, I only give you the key and the func, you handle the rest.

A lightweight factory pattern has methods only, but the more standard version passes a whole class in.

```C#
// C# uses the built-in Func, no need to define your own
TValue GetOrAdd(TKey key, Func<TKey, TValue> factory)
```

```TS
// TS uses an arrow function type, no need to define anything either
function getOrAdd<TKey, TValue>(key: TKey, factory: (key: TKey) => TValue): TValue
```

The interface form works too

```TS
// defined with an interface
interface Factory<TKey, TValue> {
    (key: TKey): TValue;  // call signature syntax
}

// function type, the return value sits on the right of the arrow, not inside <>
// look closely and the shape here is about the same as the interface above, the parens stand for the function
type Func<TKey, TValue> = (key: TKey) => TValue;
```

Wrapping `(key: TKey): TValue` in () means this is a function, and `TValue` declares its return type. But for the interface as a whole, those types have to come from outside, which is why there's `<TKey, TValue>`. This part is easy to mix up. C#'s `Func` type takes the last generic as the output type by default, and ts doesn't work that way.

---

**Translation note.** I wrote this in Chinese. This English version is an LLM translation, so the wording is not mine even though the thinking is. Original: [工廠模式](</zh-hant/posts/工廠模式>).
