Encapsulation Patterns

Patterns That Provide Forms of Encapsulation

Sometimes you want to encapsulate a group of classes in order to implement an abstract view of their combined functionality. Often when this is done you may still want to be able to be able to access the classes directly.

Sometimes you just want to define an abstract behavior that has several variations. That is, you want to encapsulate several algorithms that share a common interface to make them interchangeable.

Patterns That "Violate" Encapsulation

Sometimes you need to "violate" encaplsulation at a low level in order to do a better job of encapsulation at a higher level. Although this sounds contradictory, the improvement arises from the fact that allowing higher level classes to directly access data in lower level classes or vice-versa avoids having to declare public methods for the access.

For this reason, well-designed OOLs have mechanisms that allow one class to have access to private members of another class. In C++, for example, you can declare one class as a "friend" of another class. In Java, a class can be nested inside of another class, which allows both classes to access private members of the other class.