# Abstract Factory — Design Patterns

Source: https://www.skillbyai.com/en/design-patterns/c-abstract

> Create families of objects that belong together.

## Consistent families

**Intent:** provide an interface for creating a *family* of related objects without naming their concrete classes, so the products always match. Classic examples are UI toolkits (buttons, inputs and dialogs for one platform or theme) or cloud providers (a queue, a blob store and a secrets client for the same vendor). The client receives one factory and asks it for each product. **Use it when** mixing products from different families would be a bug and you genuinely support several families. **Avoid it when** you support one family; it adds an interface per product plus a factory interface. In modern code the "factory" is often just an object of creation functions, or the job is done by a dependency injection container configured per environment.

## Cloud provider family

Each factory creates matching clients.

```typescript
interface Queue { send(msg: string): Promise<void>; }
interface BlobStore { put(key: string, data: Uint8Array): Promise<void>; }

interface CloudFactory {
  createQueue(name: string): Queue;
  createBlobStore(bucket: string): BlobStore;
}

class AwsFactory implements CloudFactory {
  createQueue(name: string) { return new SqsQueue(name); }
  createBlobStore(bucket: string) { return new S3BlobStore(bucket); }
}

class InMemoryFactory implements CloudFactory {   // for tests and local dev
  createQueue() { return new InMemoryQueue(); }
  createBlobStore() { return new InMemoryBlobStore(); }
}

function buildApp(cloud: CloudFactory) {
  const jobs = cloud.createQueue('image-jobs');
  const images = cloud.createBlobStore('images');
  return new ImageService(jobs, images);   // never mixes vendors
}
```

## A furniture collection

Ordering from one furniture collection guarantees the chair, table and sofa match. Abstract Factory is choosing the collection once, then ordering each piece from it.

**Quiz:** What problem does Abstract Factory specifically solve?

- [ ] Ensuring a class has one instance
- [x] Creating related objects that must belong to the same family
- [ ] Adding behaviour to an object at runtime
- [ ] Iterating over a collection

*Answer:* Creating related objects that must belong to the same family. It keeps product families consistent.
