-
Notifications
You must be signed in to change notification settings - Fork 12
/
flyweight.cr
80 lines (70 loc) · 2.29 KB
/
flyweight.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# The flyweight pattern is a design pattern that is used to minimise
# resource usage when working with very large numbers of objects.
# When creating many thousands of identical objects, stateless flyweights
# can lower the memory used to a manageable level.
alias Position = {Int32, Int32}
# Contains the extrinsic actions that the object can do.
abstract class FlyweightTree
abstract def draw_at(pos : Position)
end
# Implements the Flyweight interface, optionally keeping an extrinsic state
# which can be manipulated via that interface.
class Tree < FlyweightTree
property pos
def initialize(species : String)
# Intrinsic (stateless) properties. These are shared between all instances of this tree.
@species = species
# Estrinsic (stateful) properties. These are accessed via the abstract interface
# provided by FlyweightTree
@pos = {0, 0}
end
def draw_at(pos : Position)
puts "Drawing #{@species} at #{pos}"
end
end
# Factory class for the flyweight objects.
class Forest
def initialize
@trees = {} of String => FlyweightTree
end
def get_tree(species : String)
if @trees.has_key?(species)
@trees[species]
else
Tree.new(species).tap { |tree| @trees[species] = tree }
end
end
def tot_instances
@trees.size
end
end
# Client code
forest = Forest.new
forest.get_tree("birch").draw_at({5, 6})
forest.get_tree("acacia").draw_at({3, 1})
forest.get_tree("magnolia").draw_at({15, 86})
forest.get_tree("birch").draw_at({8, 15})
forest.get_tree("acacia").draw_at({18, 4})
forest.get_tree("baobab").draw_at({1, 41})
forest.get_tree("magnolia").draw_at({80, 50})
forest.get_tree("acacia").draw_at({22, 3})
forest.get_tree("birch").draw_at({1, 42})
forest.get_tree("baobab").draw_at({15, 7})
forest.get_tree("acacia").draw_at({33, 49})
forest.get_tree("magnolia").draw_at({0, 0})
puts "-----------------------"
puts "Total instances created: #{forest.tot_instances}"
# Drawing birch at {5, 6}
# Drawing acacia at {3, 1}
# Drawing magnolia at {15, 86}
# Drawing birch at {8, 15}
# Drawing acacia at {18, 4}
# Drawing baobab at {1, 41}
# Drawing magnolia at {80, 50}
# Drawing acacia at {22, 3}
# Drawing birch at {1, 42}
# Drawing baobab at {15, 7}
# Drawing acacia at {33, 49}
# Drawing magnolia at {0, 0}
# -----------------------
# Total instances created: 4