The Flyweight Pattern – Classification of Data



The Flyweight Pattern – Classification of Data

0 0


presentation-flyweight


On Github Heath101 / presentation-flyweight

The Flyweight Pattern

Created by Heath Attig

Design Patterns

General reusable solution to a commonly occurring problem within a given context

What is the flyweight pattern?

  • a structural design pattern

  • a way to minimize memory by sharing as much data with similar objects.

Example

building a forest for a game

Classification of Data

There are 2 types of data

Intrinsic

Extrinsic

Example

Let's decorate a Christmas tree

Lamp

the flyweight object

# Flyweight Object
class Lamp
  attr_reader :color

  def initialize(color)
    @color = color
  end
end

Tree Branch

class TreeBranch
  def initialize(branch_number)
    @branch_number = branch_number
  end

  def hang(lamp)
    puts "Hang #{lamp.color} lamp on branch #{@branch_number}"
  end
end

Lamp Factory

# Flyweight Factory
class LampFactory
  def initialize
    @lamps = {}
  end

  def find_lamp(color)
    if @lamps.has_key?(color)
      # if the lamp already exists, reference it instead of
      # creating a new one
      lamp = @lamps[color]
    else
      lamp = Lamp.new(color)
      @lamps[color] = lamp
    end
    lamp
  end

  def total_number_of_lamps_made
    @lamps.size
  end
end

Christmas Tree

class ChristmasTree
  def initialize
    @lamp_factory = LampFactory.new
    @lamps_hung = 0

    dress_up_the_tree
  end

  def hang_lamp(color, branch_number)
    TreeBranch.new(branch_number).hang(@lamp_factory.find_lamp(color))
    @lamps_hung += 1
  end

  def dress_up_the_tree
    hang_lamp('red', 1)
    hang_lamp('blue', 1)
    hang_lamp('yellow', 1)
    hang_lamp('red', 2)
    hang_lamp('blue', 2)
    hang_lamp('yellow', 2)
    hang_lamp('red', 3)
    hang_lamp('blue', 3)
    hang_lamp('yellow', 3)
    hang_lamp('red', 4)
    hang_lamp('blue', 4)
    hang_lamp('yellow', 4)
    hang_lamp('red', 5)
    hang_lamp('blue', 5)
    hang_lamp('yellow', 5)
    hang_lamp('red', 6)
    hang_lamp('blue', 6)
    hang_lamp('yellow', 6)
    hang_lamp('red', 7)
    hang_lamp('blue', 7)
    hang_lamp('yellow', 7)
    puts "Made #{@lamp_factory.total_number_of_lamps_made} total lamps"
  end
end

A few examples in the wild

  • Resources fetched for a page
  • Event bubbling in javascript

Thats all.

The Flyweight Pattern Created by Heath Attig