Strategy Design Pattern in ABAP
This is a series that will investigate various design patterns and how they can be used in ABAP Objects.
After reading the excellent series of articles by Andreas Blumenthal and Horst Keller, I decided that my next project would be written using ABAP Objects. At the same time, I am learning about design patterns to help me better design and maintain my programs. As I read about a pattern, I try to think about the practical applications of the pattern. Then I try to find some code that I can rewrite with this application in mind.
I thought that I would share my experience with you so that you could share your experience with me. As I am just learning about ABAP objects and design patterns, perhaps I am not applying the principles properly, or someone sees something that would be better. I hope that you enjoy the series and that we can all learn from each other.
The Strategy pattern defines a family of algorithms, encapsulates each one and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.(1)
Encapsulate the concept that varies. Program to an interface, not an implementation.
In order to implement the strategy pattern you need to follow these steps:
- Implement a Strategy interface for your strategy objects.
- Implement ConcreteStrategy classes that implement the Strategy interface.
- In the Context class, maintain a private reference to a Strategy object.
- In the Context class, implement the methods for the Strategy object.
In my case I have a file that comes from our cash register machines. The file has a header line and various record lines. The data on the record line varies. Some record lines show sales by the hour. Some show sales by clerk. Others show the materials sold. And still other lines hold information on the machine itself, like its name and the date and time of the close out.
This file needs to be loaded into SAP so that sales orders can be created and the revenue recognized. Following the first guiding principle, I figured that this would be the perfect candidate for the strategy pattern, where the record line would be the context and the parsing logic and data upload could be handled in the ConcreteStrategy classes. I could go further, because each record line then has various fields with different field types. But I think this is enough for my poor brain for now.
Here are two UML diagrams. One shows a generic implementation of the strategy pattern(2), and the other shows how it is used with the file upload.
Here is the ABAP Code to implement the strategy.
(1)Head First Design Patterns, Eric Freeman and Elisabeth Freeman
(2)DO Factory (http://www.dofactory.com/Patterns/PatternStrategy.aspx)