This article describes how to implement the Composite design pattern [1] in Apex. The Composite Design Pattern in Apex allows for representation of expressions, such as;

  • 1 AND 2
  • 1 OR (2 AND 3)
  • (1 AND 2) OR ((3 OR 4) AND 5)

For the parent page to this article, and for a full list of other design patterns, go to Apex Design Patterns.


Our developer has a requirement to create custom version of the Create/Edit List View screen. However, he is really struggling with how to represent an expression (outlined in red). The difficulty is due to the level of recursion involved.


Note: This article will not cover developing the actual screen or parsing the expression - this article is limited to representing an expression in Apex.


Composite uml.jpg


To implement the Composite Design Pattern, deploy the following interface and classes in your environment.

Expression Interface

Composite class

AndComposite Class

OrComposite class

Variable class



The below examples illustrate how to use the Expression interface.

Example: 1 AND 2

Example: 1 OR (2 AND 3)

Example: Method Chaining

Example: 1 OR (2 AND 3)


The Composite design pattern can be used to represent an expression in Apex regardless of expression complexity, whilst mitigating the impact of governor limits that can result from recursions.

See the Apex Design Patterns article for more design patterns.