Patterns

These simplified version of the classic software development patterns are used to give defined roles and responsibilities to your Apex code, and to help organise the code base.

Factory Method

The Factory is a creational design pattern for creating objects. It defines a method which we can use to create an object instead of using its constructor.

public with sharing class ProductFactory {

    public static Product2 createProduct() {

        Product2 product = new Product();
        
        // set all properties 
        
        return product;        
    }
}

Service Layer

The service re-usability principle dictates that services should be designed to maximise reuse. A service contain only a specific type of logic e.g., either reusable or process-specific logic.

The service is responsible for business logic / orchestration, and the service cam be used by different consumers.

public with sharing class CommunityService {

    public static void createPortalUser(Id accountId) {
        // so something
    }
}

This service method createPortalUser can be used by various consumers:

  • Trigger

  • Invocable Method

  • Email Handler

  • AuraEnabled Method

  • Batchable

  • Queueable

  • Scheduleable

Therefore the service is agnostic of the consumer.

Data Access Layer

The data access layer contains all your SOQL queries.

public with sharing class ContactDataAccess {

    public static List<Contact> getContactsByStatus(Boolean status) {

        return [SELECT Id,
                       FirstName,
                       LastName,
                       Email,
                       Mobile
                       FROM Contact
                       WHERE Status__c = :status]
    }
}

Provider Pattern

Command Pattern

Builder Pattern

The builder pattern is used to build objects. The objects can be complex, made up of several sub-objects or require an elaborate construction process. The exercise of creating complex types can be simplified by using the builder pattern.

Strategy Pattern

The strategy pattern allows grouping related algorithms under an abstraction, which allows switching out one algorithm or policy for another without modifying the client. Instead of directly implementing a single algorithm, the code receives run-time instructions specifying which of the group of algorithms to run.

Adaptor Pattern

This allows incompatible classes to work together by converting the interface of one class into another. Think of it as a sort of translator: when two heads of states who don’t speak a common language meet, usually an interpreter sits between the two and translates the conversation, thus enabling communication.

If you have two applications, with one spitting out output as XML with the other requiring JSON input, then you’ll need an adaptor between the two to make them work seamlessly.

Decorator Pattern

Facade Pattern

Proxy Pattern

Last updated