Search code examples
design-patternssingleton

Name of design pattern creating the same object for equal arguments


It's a bit like the singleton pattern with the twist that one passes arguments when acquiring the object and are getting the same object if and only if the arguments are the same. Example in python:

a = get_object(42)
b = get_object(42)
c = get_object(19)

a is b
a is not c

Solution

  • Function having the following properties:

    • return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams, i.e., referential transparency)
    • has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or input/output streams).

    Is called pure. For pure functions you can apply the memoization:

    In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls to pure functions and returning the cached result when the same inputs occur again.