“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification” – one of the basic principles of OOAD states.
This is especially valuable in a production environment, where changes to source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: code obeying the principle doesn't change when it is extended, and therefore needs no such effort.Use of abstracted interfaces, where the implementations can be changed and multiple implementations could be created and polymorphic ally substituted for each other is normally followed as an approach for OCP.
In this article I will explain the Visitor* pattern implementation as a solution approach for the OCP.
* “The Visitor pattern defines and performs new operations on all the elements of an existing structure, without altering its classes”
The implementation of Visitor pattern involves two interfaces/ abstract classes (IVisitor and IElement) as shown in the class diagram below
The Visitor pattern has two distinct parts: there are the classes that make up an object structure, and then there are the methods that will be applied to the object structure. These are the visitors. The object structure is specified by a hierarchy of Element classes.