DEV Community

Sergey Leschev
Sergey Leschev

Posted on • Updated on

🍃 Flyweight Pattern

Flyweight Pattern

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.



// Instances of SpecialityCoffee will be the Flyweights
struct SpecialityCoffee {
    let origin: String

protocol CoffeeSearching {
    func search(origin: String) -> SpecialityCoffee?

// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
final class Menu: CoffeeSearching {

    private var coffeeAvailable: [String: SpecialityCoffee] = [:]

    func search(origin: String) -> SpecialityCoffee? {
        if coffeeAvailable.index(forKey: origin) == nil {
            coffeeAvailable[origin] = SpecialityCoffee(origin: origin)

        return coffeeAvailable[origin]

final class CoffeeShop {

    private var orders: [Int: SpecialityCoffee] = [:]
    private let menu: CoffeeSearching

    init(menu: CoffeeSearching) { = menu

    func takeOrder(origin: String, table: Int) {
        orders[table] = origin)

    func serve() {
        for (table, origin) in orders {
            print("Serving \(origin) to table \(table)")
Enter fullscreen mode Exit fullscreen mode


let coffeeShop = CoffeeShop(menu: Menu())

coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)

Enter fullscreen mode Exit fullscreen mode

Sources: Github

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

🐝 Chain Of Responsibility
👫 Command Pattern
🎶 Interpreter Pattern
🍫 Iterator Pattern
💐 Mediator Pattern
💾 Memento Pattern
👓 Observer Pattern
🐉 State Pattern
💡 Strategy Pattern
📝 Template Method
🏃 Visitor Pattern
🌰 Abstract Factory
👷 Builder Pattern
🏭 Factory Method
🔂 Monostate Pattern
🃏 Prototype Pattern
💍 Singleton
🔌 Adapter Pattern
🌉 Bridge Pattern
🌿 Composite Pattern
🍧 Decorator Pattern
🎁 Facade Pattern
🍃 Flyweight Pattern
Protection Proxy
🍬 Virtual Proxy

I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.

🛩️ #startups #management #cto #swift #typescript #database
📧 Email:
👋 LinkedIn:
👋 LeetCode:
👋 Twitter:
👋 Github:
🌎 Website:
🌎 Reddit:
🌎 Quora:
🌎 Medium:
🖨️ PDF Design Patterns: Download

Top comments (0)