Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiton pattern vs flyweight pattern

I cannot see any single difference between Multiton and Flyweight patterns. Please explain what is the difference?

like image 407
Narek Avatar asked Jan 10 '23 15:01

Narek


1 Answers

The patterns have a similar result, but this is almost by coincidence as the intent is different.

For me, the main intent of the flyweight is to reduce memory by sharing state.

The main intent of multition is to always have the exact same instance (singleton) of an object returned when you use the same key to get the instance.

  • Multition
    • Guarantees that only one instance of an object will exist for any key, like a singleton-per-key model
  • Flyweight
    • Reduces memory consumption by sharing state between objects.

The classic example of a flyweight is in a word processor where each letter is represented by an object and in order to avoid creating many objects for each letter instead only one instance of each letter exists.

It may be possible to implement this by using a multition which ensures that for the key 'A' the same instance of the object representing 'A' is returned. In this case the patterns do indeed both seem similar.

But the flyweight makes no demand that only a single instance may exist (a requirement for the multition pattern). So it may also be possible to have an implementation of a word processor where you had an instance of each letter object per document.

This would still massively reduce the amount of memory and I believe would still be an instance of the flyweight pattern, but would not not be the multition pattern, as many instances of the letter 'A' could exist in different documents.

You could also use the flyweight pattern to reduce memory consumption in many other situations where the multition pattern would not be applicable. This might not be a perfect example, but imagine a system which provides lists of students at a school and the classes they take. If you have a student object which contains a list of classes the student takes and the classes list the room, the teacher, the available equipment etc etc.

In a naive model the student may have a collection of Class objects and each Class object would be created new for each student. You are storing many objects on each student and this may require a lot of memory. Instead you could use a flyweight for the Class and store only the reference to the same Class instance in each student that takes the class. This would significantly reduce the memory required to store a large list of students.

But it might not be appropriate for the Class instances to be singletons as the classes themselves are data driven and dynamic (new classes can be added and removed etc) and so the multition pattern would not be an appropriate fit here.

like image 133
Sam Holder Avatar answered Feb 12 '23 11:02

Sam Holder