I am tasked to write an assembler in C, which lends itself sufficiently well in certain design-pattern scenarios, and in a parsing phase, after tokenization, I need to "fill-in" certain information that was previously ignored by tokenization.

I'll skip details, but the way I thought to solve this is by having a sole instance of an object (concretely, a structure) that is equal with another. For example, given:

typedef struct {
    unsigned int day, month, year;
} day;

day *a = singleton_day(9, 3, 1999), *b = singleton_day(9, 3, 1999);

a and b will be pointers to the same memory location, as they were instantiated with identical values.

This technique is going to have a beneficial impact on space and algorithmic performance of my code, but I don't know how to call the instantiation primitives. I'd like to inspire on an alleged design pattern, but I don't know if it exists or if I should make one up.

  • 3
    Yes the multi-instance singleton pattern has been documented. It's aptly named multiton. – Nick Alexeev Nov 18 '18 at 20:14
  • Be aware that you'll have to mangage the existing elements, though - most simplest within an array, iterating over to check if an element exists already. Hashing might be faster if there are numerous elements. If your struct is comparably simple as your day struct, I doubt it is worth the effort, though... – Aconcagua Nov 18 '18 at 20:18
  • Looks like the Flyweight pattern – Vincent Savard Nov 23 '18 at 19:22

The term singleton is not appropriate for what you are trying to convey. A much better word is "unique". You want to get a unique reference to a value class.

The value class has only constant value members. That means that two instances of the value class that have the same members would always compare as equal. Since they are always equal values, then references to them should also be equal.

A factory would create an instance of the value class if no previous instance of the class exists, or return a reference to the previous instance.

There are a number of methods for managing instances used by the factory. One common example is using a hash map from the field values to the unique instance. However, any caching method will do the job.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.