Design Patterns Handbook
  • Introduction
  • Creational Patterns
    • Builder
    • Factory
    • Abstract Factory
    • Factory Method
    • Prototype
    • Singleton
    • Object Pool
    • Revealing Constructor
  • Structural Patterns
    • Adapter
    • Composite
    • Proxy
    • Flyweight
    • Facade
    • Bridge
    • Decorator
    • Private Class Data
  • Behavioral Patterns
    • Template Method
    • Mediator
    • Chain Of Responsibility
    • Observer
    • Strategy
    • Command
    • State
    • Visitor
    • Memento
    • Interpreter
    • Null Object
    • Iterator
    • Middleware
  • Clean Code Patterns
    • Extract Method
    • Clarify Responsibility
    • Remove Duplications
    • Keep Refactoring
    • Always Unit Test
    • Create Data Type
    • Comment to Better Name
    • Consistent Naming
    • If-else over ternary operator
    • Composition over Inheritance
    • Too Many Returns
    • Private to Interface
  • Anti Patterns
    • Big Ball of Mud
    • Singleton
    • Mad Scientist
    • Spaghetti Code
    • It Will Never Happen
    • Error Codes
    • Commented Code
    • Abbreviations
    • Prefixes
    • Over Patternized
    • Generic Interface over Function
Powered by GitBook
On this page

Was this helpful?

  1. Structural Patterns

Flyweight

Flyweight is inteded to use sharing to support large numbers of fine-grained objects efficiently.

Good example to explain usage Flyweight is UIKit by Apple. When we create TableView that is can display milions rows to the user, we know that user can see only few at the time. What Apple engineers did that they are reusing components that are on the table view to avoid any performance issues.

Example - UI component factory

When our UI table should display a button, it will use ButtonFactory to get a button (keeping track of what buttons are not used and visible is omitted). Number that is the parameter in get method could be an ID of a button in a table row (but it is not really important in this example).

This example intent is to show that Flyweight is some kind of cash for objects that are memory-heavy or difficult to create.

class Button {
}

class ButtonFactory {

    private Map<Integer, Button> cache = new HashMap<>();

    public Button get(Integer number) {
        if (cache.containsKey(number)) {
            return cache.get(number);
        } else {
            Button button = new Button();
            cache.put(number, button);
            return button;
        }
    }
}

Then we would use the factory whenever we need an instance of a button that can be reused.

ButtonFactory buttonFactory = new ButtonFactory();

Button button1a = buttonFactory.get(1);
Button button1b = buttonFactory.get(1);
PreviousProxyNextFacade

Last updated 5 years ago

Was this helpful?