In part 11 of Design pattern series we will go into creating and using the Bridge design pattern. It is moderately used and uses encapsulation, inheritance and aggregation to separate responsibilities into other classes.

The Bridge pattern decouples an abstraction from its implementation so that the two can vary independently.

Usage

The pattern is most useful, when both classes (implementation and abstraction) are assigned to different task handling. In our example, we will look at how to separate data and actions to build a list of products and navigate it.

Data representation class

This is an abstract class with only navigational methods specified. Data representation class must implement navigational logic in its methods and thus assures that no other class will change or handle any properties without data representation class knowledge.

Also, for needs of our example, we will also define a type that will contain product id, name and price.

Product data class

Class itself inherits from Data representation abstract class. Also, it contains all navigational logic as well as data handling.

Beware that for this example, I did not actually load the data from the database. Instead I created five (5) products in the class construct. In real life, you should have read the data from your database!

Product base class

Now, that we have our data classes created, we need to build an abstraction class that will call actual navigation and display the list contents or item if necessary. As we might have multiple classes that should have same functionality, it is a must to create a base class first. This class will encapsulate Data representation abstract class.

Concrete product class

Concrete product class in our case, will only be used to alter presentation when ShowAll method is called. This is not a must.

Implementation

For test purposes, I have created an agent that will:

  • create product list
  • navigate forward and backward
  • add an item to the list
  • remove an item from the list
  • display single product or all products at any time,