How-to use the Singleton-Pattern in Mendix

Max Bareis
2 min readDec 1, 2020

The Singleton pattern is one of the creational pattern developed by the Gang of Four (GOF) Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. It describes a class that has only one object and provides a global access point to that class.

UML Class diagram exemplifying the singleton pattern (source: Wikipedia)

Singletons are often used instead of global variables. For example if you need different Server configurations in your staging environment as you do not want your test space on localhost connect to a productive external data source, then the singleton comes in handy.

In the Mendix environment it is not possible to create strict Singletons as an entity could always be created multiple times in different microflows. You have to follow the pattern as convention. So lets start with creating the Configuration Entity:

First step to establish the convention is to create a microflow with a lazy entity creation:

Second step to establish the convention is to make sure that you never retrieve the entity through database or xpath but only through above microflow. To manage the configuration create a page with a dataView that retrieves the configuration through the microflow:

If you want to access the configuration also make sure to use the microflow to retrieve the configuration:

So this is it. The singleton pattern low code style.

Update:

Joost Stapersma@Mansystems and Pieter van de Braak suggested to eliminate the risk of having a race condition when two users access the microflow at exactly the same time. We discussed if the addition of an _id with a unique validation rule and a default value would solve the problem, but this would probably only throw an error. Calling the microflow at startup of the server would solve the issue as the singleton is created before any access can be possibly made.

--

--

Max Bareis

Full Stack Developer. Building digital things from the early 90s until now. Currently focused on low code development.