Design Patterns in ABAP

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A design pattern is a well-known way to arrange a few classes so that a common problem stays easy to solve and easy to change. It is not a library and not a statement of the language; it is a recipe that programmers in every object-oriented language recognise and name, so that "use a factory here" is enough to explain the shape of the code. This page shows five patterns that appear again and again in ABAP programs and in the SAP standard code: the factory, which hides how an object is created; the singleton, which allows only one object of a class; the strategy, which lets you swap a rule without changing the code that uses it; the observer, which lets one object announce a change to others through ABAP events; and dependency injection, which hands an object what it needs from outside so that a test can supply a stand-in. The examples use the Expense claims program of this section and are written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Classes, interfaces, events and ABAP Unit belong to the core language, so everything here applies in ABAP Cloud, in classic Standard ABAP, on premise and in the Public Edition alike.

Before you read

  • Classes and interfaces: you should have seen a class with a DEFINITION and an IMPLEMENTATION, a method call and an interface with INTERFACES. A page of this section on classes and interfaces covers them in depth.

  • Memory Organization and Sessions: the singleton section relies on the fact that an object lives in one internal session.

  • Constructor Expressions: NEW, COND and CONV are used in the examples.

  • A page on ABAP Unit tests of this section covers test classes in depth; here a test is shown only to explain why injection helps.

Key terms

  • Design pattern: a named, reusable arrangement of classes that solves a problem which comes up often.

  • Interface: a list of method signatures that several classes can promise to implement, so that callers depend on the list and not on one class.

  • Factory method: a static method whose job is to create and return an object, so that the caller does not need to know which class is built.

  • Singleton: a class written so that only one object of it exists in the running program.

  • Strategy: one of several interchangeable classes that all implement the same interface, chosen at run time.

  • Event: a signal that an object raises with RAISE EVENT and that other objects react to through a handler method.

  • Dependency injection: giving an object the other objects it needs from outside, usually through its constructor, instead of letting it create them itself.

  • Test double: a simple stand-in object that a unit test passes in place of a real collaborator, so that the test controls what the collaborator answers.

The idea behind most patterns: depend on an interface

Almost every pattern on this page rests on one habit: the code that uses an object talks to an interface, never to a concrete class. An interface declares methods without code; each class that implements it supplies the code. A caller that only knows the interface works unchanged with any new class that implements it. The five patterns are variations of where that class comes from (factory, singleton), which one is picked (strategy), who is told about changes (observer) and how a test gets to choose it (injection).

The running example is the approval of an expense claim. A claim of up to 500.00 is approved automatically; larger claims need a manager. The rule can change per company or per country, so it is the part that must be easy to swap. The diagram shows the classes the page builds up: the interface lif_policy, two strategies that implement it, a service that is handed a policy, and a test double that replaces it in a test.

classDiagram class lif_policy { <<interface>> +approves(amount) abap_bool } class lcl_standard_policy { +approves(amount) abap_bool } class lcl_manager_policy { +approves(amount) abap_bool } class ltd_policy { +answer abap_bool +approves(amount) abap_bool } class lcl_claim_service { +submit(amount) string } lif_policy <|.. lcl_standard_policy lif_policy <|.. lcl_manager_policy lif_policy <|.. ltd_policy lcl_claim_service --> lif_policy : uses

Names follow the usual convention: lif_ for a local interface, lcl_ for a local class, ltd_ for a test double and ltc_ for a test class. The examples use local classes in a report so that each listing is complete in one piece; in a real project the classes are global (zif_..., zcl_...) or local to a global class, and the patterns are the same.

Strategy: swap a rule without changing the caller

A strategy is one of several classes that implement the same interface. The code that needs the rule holds a reference to the interface and calls its method; which class stands behind the reference decides the result. For expense claims the interface lif_policy has one method, approves, and there is a standard policy with a limit of 500.00 and a manager policy with a limit of 5000.00.

The report below creates each policy in turn, assigns it to the same reference variable policy and asks the same question. The statement NEW lcl_standard_policy( ) creates an object and, because the target is a reference to the interface, the assignment is allowed. The code that calls approves never mentions a class. It runs in the local playground and prints the lines below.

REPORT zp_strategy.

TYPES ty_amount TYPE p LENGTH 8 DECIMALS 2.

INTERFACE lif_policy.
  METHODS approves IMPORTING amount TYPE ty_amount RETURNING VALUE(result) TYPE abap_bool.
ENDINTERFACE.

CLASS lcl_standard_policy DEFINITION FINAL.
  PUBLIC SECTION.
    INTERFACES lif_policy.
ENDCLASS.

CLASS lcl_standard_policy IMPLEMENTATION.
  METHOD lif_policy~approves.
    result = xsdbool( amount <= 500 ).
  ENDMETHOD.
ENDCLASS.

CLASS lcl_manager_policy DEFINITION FINAL.
  PUBLIC SECTION.
    INTERFACES lif_policy.
ENDCLASS.

CLASS lcl_manager_policy IMPLEMENTATION.
  METHOD lif_policy~approves.
    result = xsdbool( amount <= 5000 ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA policy TYPE REF TO lif_policy.

  policy = NEW lcl_standard_policy( ).
  WRITE / |standard policy, 1200.00: { COND string( WHEN policy->approves( CONV #( '1200.00' ) ) = abap_true
                                        THEN `approved` ELSE `needs a manager` ) }|.

  policy = NEW lcl_manager_policy( ).
  WRITE / |manager policy,  1200.00: { COND string( WHEN policy->approves( CONV #( '1200.00' ) ) = abap_true
                                        THEN `approved` ELSE `needs a manager` ) }|.
standard policy, 1200.00: needs a manager
manager policy,  1200.00: approved

The same claim is judged differently because a different object answers. Adding a third rule, for example a policy per cost centre, means writing one more class that implements lif_policy; no existing caller changes. This is the open-closed idea in practice: open for new rules, closed for edits of working code. Compare it with the alternative, a long CASE on a country code inside one method, which grows with every new rule and has to be retested as a whole.

Factory: hide which class is created

Somebody has to decide which strategy to build. If every caller writes NEW lcl_manager_policy( ) itself, each caller knows every class, and a new class means editing many places. A factory collects that decision in one place. The most common form in ABAP is a static factory method, declared with CLASS-METHODS, that takes a description of what is wanted and returns a reference to an interface.

Two ABAP features support this. A class declared with CREATE PRIVATE can be instantiated only from inside the class itself or from the friends it names, so outsiders have no choice but to go through the factory. The addition FRIENDS names a class that is allowed past that restriction; a local class that is used before its declaration is announced with DEFINITION DEFERRED. The examples also mark these classes FINAL, because nothing is meant to inherit from them.

The example exports one claim line in two formats. The interface lif_exporter has one method, the two exporters implement it, and lcl_exporter_factory=>create picks the class from the format name and raises an exception for a format it does not know. The exception class lcx_unknown_format inherits from cx_static_check, so the method declares it with RAISING and the caller must handle it. It runs in the local playground and prints the lines below.

REPORT zp_factory.

INTERFACE lif_exporter.
  METHODS export IMPORTING claim_id TYPE string
                           amount   TYPE string
                 RETURNING VALUE(line) TYPE string.
ENDINTERFACE.

CLASS lcx_unknown_format DEFINITION FINAL INHERITING FROM cx_static_check.
ENDCLASS.

CLASS lcl_exporter_factory DEFINITION DEFERRED.

CLASS lcl_csv_exporter DEFINITION FINAL CREATE PRIVATE FRIENDS lcl_exporter_factory.
  PUBLIC SECTION.
    INTERFACES lif_exporter.
ENDCLASS.

CLASS lcl_csv_exporter IMPLEMENTATION.
  METHOD lif_exporter~export.
    line = |{ claim_id };{ amount }|.
  ENDMETHOD.
ENDCLASS.

CLASS lcl_text_exporter DEFINITION FINAL CREATE PRIVATE FRIENDS lcl_exporter_factory.
  PUBLIC SECTION.
    INTERFACES lif_exporter.
ENDCLASS.

CLASS lcl_text_exporter IMPLEMENTATION.
  METHOD lif_exporter~export.
    line = |Claim { claim_id } for { amount }|.
  ENDMETHOD.
ENDCLASS.

CLASS lcl_exporter_factory DEFINITION FINAL.
  PUBLIC SECTION.
    CLASS-METHODS create
      IMPORTING format        TYPE string
      RETURNING VALUE(result) TYPE REF TO lif_exporter
      RAISING   lcx_unknown_format.
ENDCLASS.

CLASS lcl_exporter_factory IMPLEMENTATION.
  METHOD create.
    CASE format.
      WHEN `csv`.
        result = NEW lcl_csv_exporter( ).
      WHEN `text`.
        result = NEW lcl_text_exporter( ).
      WHEN OTHERS.
        RAISE EXCEPTION NEW lcx_unknown_format( ).
    ENDCASE.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  TRY.
      WRITE / lcl_exporter_factory=>create( `csv` )->export( claim_id = `C-1001` amount = `120.50` ).
      WRITE / lcl_exporter_factory=>create( `text` )->export( claim_id = `C-1001` amount = `120.50` ).
      WRITE / lcl_exporter_factory=>create( `xml` )->export( claim_id = `C-1001` amount = `120.50` ).
    CATCH lcx_unknown_format.
      WRITE / `unknown format: xml`.
  ENDTRY.
C-1001;120.50
Claim C-1001 for 120.50
unknown format: xml

In practice you also meet static creation methods on the class itself, for example a method from_file or from_text that returns a new instance of its own class, next to a private constructor. The Clean ABAP style guide recommends several named creation methods over one constructor with many optional parameters, because the name tells the reader what is being built. The factory above is the variant to use when the caller should receive an interface, not a class.

Singleton: one object for the whole program

A singleton is a class of which at most one object exists. The class keeps the single object in a static attribute declared with CLASS-DATA, makes its constructor private with CREATE PRIVATE so nobody can call NEW from outside, and offers a static method, conventionally named get_instance, that creates the object the first time it is asked and returns the same object every time afterwards. Typical uses are settings that are read once, such as the approval limit in the example.

The report asks for the instance twice and then changes the limit through the first reference. The second reference sees the change because both point to the same object. It runs in the local playground and prints the lines below.

REPORT zp_singleton.

CLASS lcl_settings DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS get_instance RETURNING VALUE(result) TYPE REF TO lcl_settings.
    DATA approval_limit TYPE i READ-ONLY.
    METHODS change_limit IMPORTING new_limit TYPE i.
  PRIVATE SECTION.
    CLASS-DATA instance TYPE REF TO lcl_settings.
ENDCLASS.

CLASS lcl_settings IMPLEMENTATION.
  METHOD get_instance.
    IF instance IS NOT BOUND.
      instance = NEW #( ).
      instance->approval_limit = 500.
    ENDIF.
    result = instance.
  ENDMETHOD.

  METHOD change_limit.
    approval_limit = new_limit.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA(first)  = lcl_settings=>get_instance( ).
  DATA(second) = lcl_settings=>get_instance( ).

  WRITE / |same object: { xsdbool( first = second ) }|.

  first->change_limit( 800 ).
  WRITE / |limit seen through the second reference: { second->approval_limit }|.
same object: X
limit seen through the second reference: 800

The line same object: X shows an ABAP convention: xsdbool returns the character X for true and a blank for false.

Two limits of the singleton matter in ABAP. First, "one object" means one object in one internal session. An instance of a class is part of the internal session that created it, as the page on memory organization explains, so another user, or another program started with SUBMIT, gets its own object, and the object is gone when the session ends. A singleton is therefore not a way to share data between users; use the database or shared objects for that. Second, a singleton is a global variable in disguise. Every class that calls get_instance depends on it invisibly, and a unit test cannot easily replace it, because the previous test may have left the limit at 800. For that reason new code prefers to create one object and pass it to the classes that need it, which is the last pattern of this page, and keeps the singleton for cases where the single instance is a real requirement.

Observer: tell others through events

In the observer pattern one object, the subject, announces that something happened and does not care who listens. Any number of other objects, the observers, register for the announcement. ABAP has the pattern built into the language through events. The subject declares an event with EVENTS and raises it with RAISE EVENT. An observer declares a handler method with FOR EVENT ... OF the subject’s class. SET HANDLER connects a handler to one object, and SET HANDLER with ACTIVATION abap_false removes the connection.

sequenceDiagram participant Main as Report participant Claim as lcl_claim participant Mail as lcl_mail_notifier participant Audit as lcl_audit_log Main->>Claim: SET HANDLER (Mail, Audit) Main->>Claim: approve( C-1001 ) Claim-->>Mail: RAISE EVENT approved Claim-->>Audit: RAISE EVENT approved Main->>Claim: SET HANDLER Mail ACTIVATION abap_false Main->>Claim: approve( C-1002 ) Claim-->>Audit: RAISE EVENT approved

The claim in the example knows neither the mail notifier nor the audit log. When approve raises the event, the system calls every handler that is registered at that moment. The report registers both handlers, approves one claim, removes the mail notifier and approves a second claim. It runs in the local playground and prints the lines below.

REPORT zp_observer.

CLASS lcl_claim DEFINITION FINAL.
  PUBLIC SECTION.
    EVENTS approved EXPORTING VALUE(claim_id) TYPE string.
    METHODS approve IMPORTING claim_id TYPE string.
ENDCLASS.

CLASS lcl_claim IMPLEMENTATION.
  METHOD approve.
    RAISE EVENT approved EXPORTING claim_id = claim_id.
  ENDMETHOD.
ENDCLASS.

CLASS lcl_mail_notifier DEFINITION FINAL.
  PUBLIC SECTION.
    METHODS on_approved FOR EVENT approved OF lcl_claim
      IMPORTING claim_id.
ENDCLASS.

CLASS lcl_mail_notifier IMPLEMENTATION.
  METHOD on_approved.
    WRITE / |mail: claim { claim_id } was approved|.
  ENDMETHOD.
ENDCLASS.

CLASS lcl_audit_log DEFINITION FINAL.
  PUBLIC SECTION.
    METHODS on_approved FOR EVENT approved OF lcl_claim
      IMPORTING claim_id.
ENDCLASS.

CLASS lcl_audit_log IMPLEMENTATION.
  METHOD on_approved.
    WRITE / |audit: claim { claim_id } approved|.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA(claim)    = NEW lcl_claim( ).
  DATA(notifier) = NEW lcl_mail_notifier( ).
  DATA(audit)    = NEW lcl_audit_log( ).

  SET HANDLER notifier->on_approved FOR claim.
  SET HANDLER audit->on_approved FOR claim.

  claim->approve( `C-1001` ).

  SET HANDLER notifier->on_approved FOR claim ACTIVATION abap_false.
  WRITE / `after deregistering the mail notifier:`.
  claim->approve( `C-1002` ).
mail: claim C-1001 was approved
audit: claim C-1001 approved
after deregistering the mail notifier:
audit: claim C-1002 approved

The Keyword Documentation gives three rules to remember. The order in which several handlers are called is not defined and can change while the program runs, so one handler must not depend on another having run first. A registered handler is held by a reference, so the garbage collector does not delete a handler object while it is registered; deregister handlers you no longer need. And the handlers run to the end before the raising method continues after RAISE EVENT, so a slow handler slows the raiser. Events inside one program are different from the business events and the event-driven integration of the SAP platform, which send messages between systems; this page covers only the language construct.

Dependency injection: make the class testable

A class that creates its own helpers is hard to test. If lcl_claim_service wrote NEW lcl_standard_policy( ) inside submit, a test of the service would always run the real 500.00 rule, and a test that wants "the policy says yes" would have to find an amount that the real policy happens to accept. Dependency injection reverses the arrangement: the class declares what it needs as an interface and is given an object from outside. The most common way is constructor injection, where the object arrives as a parameter of the constructor and is stored in an attribute.

In a unit test the outside world is a test double: a small class, defined in the test code, that implements the interface and answers whatever the test tells it to. The example service accepts a policy in its constructor and falls back to the standard policy when none is given, so production code can still write NEW lcl_claim_service( ). The two tests inject a double that always says yes and one that always says no, and check the service’s answer. Because lif_policy is an interface, the double needs only the one method. The two tests and the line of the report run in the local playground: both tests pass, and the report prints default policy, 120.00: approved.

REPORT zp_di.

TYPES ty_amount TYPE p LENGTH 8 DECIMALS 2.

INTERFACE lif_policy.
  METHODS approves IMPORTING amount TYPE ty_amount RETURNING VALUE(result) TYPE abap_bool.
ENDINTERFACE.

CLASS lcl_standard_policy DEFINITION FINAL.
  PUBLIC SECTION.
    INTERFACES lif_policy.
ENDCLASS.

CLASS lcl_standard_policy IMPLEMENTATION.
  METHOD lif_policy~approves.
    result = xsdbool( amount <= 500 ).
  ENDMETHOD.
ENDCLASS.

CLASS lcl_claim_service DEFINITION FINAL.
  PUBLIC SECTION.
    METHODS constructor IMPORTING policy TYPE REF TO lif_policy OPTIONAL.
    METHODS submit IMPORTING amount TYPE ty_amount RETURNING VALUE(status) TYPE string.
  PRIVATE SECTION.
    DATA policy TYPE REF TO lif_policy.
ENDCLASS.

CLASS lcl_claim_service IMPLEMENTATION.
  METHOD constructor.
    me->policy = COND #( WHEN policy IS BOUND THEN policy ELSE NEW lcl_standard_policy( ) ).
  ENDMETHOD.

  METHOD submit.
    status = COND #( WHEN policy->approves( amount ) = abap_true
                     THEN `approved` ELSE `needs a manager` ).
  ENDMETHOD.
ENDCLASS.

CLASS ltd_policy DEFINITION FINAL FOR TESTING.
  PUBLIC SECTION.
    INTERFACES lif_policy.
    DATA answer TYPE abap_bool.
ENDCLASS.

CLASS ltd_policy IMPLEMENTATION.
  METHOD lif_policy~approves.
    result = answer.
  ENDMETHOD.
ENDCLASS.

CLASS ltc_claim_service DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
  PRIVATE SECTION.
    METHODS approved_when_policy_says_yes FOR TESTING.
    METHODS escalated_when_policy_says_no FOR TESTING.
ENDCLASS.

CLASS ltc_claim_service IMPLEMENTATION.
  METHOD approved_when_policy_says_yes.
    DATA(double) = NEW ltd_policy( ).
    double->answer = abap_true.
    DATA(cut) = NEW lcl_claim_service( double ).
    cl_abap_unit_assert=>assert_equals( act = cut->submit( 9999 ) exp = `approved` ).
  ENDMETHOD.

  METHOD escalated_when_policy_says_no.
    DATA(double) = NEW ltd_policy( ).
    double->answer = abap_false.
    DATA(cut) = NEW lcl_claim_service( double ).
    cl_abap_unit_assert=>assert_equals( act = cut->submit( 1 ) exp = `needs a manager` ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  WRITE / |default policy, 120.00: { NEW lcl_claim_service( )->submit( 120 ) }|.
default policy, 120.00: approved

The Keyword Documentation advises that everything a test needs, including test doubles and helper classes, is defined only in test classes, so that it is not generated in production systems and cannot be called by production code. That is why the double is declared FOR TESTING. It also notes that the ABAP Test Double Framework, based on the class CL_ABAP_TESTDOUBLE, simplifies and standardises the creation and configuration of test doubles; it requires an SAP system, so it is not run here. Writing a double by hand, as above, is the clearest way to learn the idea.

Constructor injection is one of several ways to get a double into a class. Others are a setter method, a parameter of the method under test, a test subclass that redefines a method, and, for code that cannot be changed, test seams, which mark a section of production code that a test replaces. The ABAP cheat sheet on design patterns compares five such injection techniques. Constructor injection is the one to prefer in new code, because the dependencies are visible in the signature and a class cannot be created without them.

Choosing a pattern

  • Use a strategy when a rule has several variants that change independently of the code that uses it, and when you would otherwise write a growing CASE on a type or country code.

  • Use a factory when callers should not know which class they get, or when creation needs several steps or a decision.

  • Use a singleton only for a true single resource, and remember that it is one object per internal session, not per system.

  • Use events when the raiser must not know its listeners and several listeners may come and go. Use a plain method call when exactly one known object must react.

  • Inject dependencies through the constructor so that tests can replace them; the other patterns then compose well, for example a factory that creates the strategy a service receives.

Patterns are tools, not goals. A class with two simple variants does not need a factory, and an interface with one implementation that will never change adds reading effort for nothing. Introduce a pattern when the code has the problem the pattern solves.

Summary

  • A design pattern is a named arrangement of classes; in ABAP most of them rest on interfaces, so callers depend on the interface and not on a concrete class.

  • A strategy is one of several classes that implement the same interface and are swapped at run time.

  • A factory is a static method that decides which class to create; CREATE PRIVATE with FRIENDS forces callers to use it.

  • A singleton keeps one object in a CLASS-DATA attribute behind get_instance, but it lives per internal session and hides a global dependency, so prefer passing the object in.

  • The observer pattern is built into the language: EVENTS, RAISE EVENT and SET HANDLER; handler order is not defined and a registered handler is not garbage collected.

  • Dependency injection gives a class its collaborators through the constructor, so a unit test can pass a test double that implements the same interface.