Developing a Shopping Cart - Part 4
Part 2 and
Part 3 we
developed shopping cart using cookies, session variables and database
respectively. In this article I will illustrate how to create a single wrapper
to all he three approaches so that without any code change you can switch
between these three techniques.
How to achieve generic nature to the shopping cart?
We have three approaches of creating shopping cart. We need to provide a
generic wrapper on all of them so that we can easily switch between them without
much of a code change. To achieve this generic nature we will be using
interfaces. We will define two interfaces - IShoppingCartItem and IShoppingCart
as shown below:
public interface IShoppingCartItem
public interface IShoppingCart
int Add(string cartid,IShoppingCartItem item);
int Remove(string cartid,IShoppingCartItem item);
ArrayList GetItems(string cartid);
The first interface will be implemented by a class that represents a shopping
cart item. The second interface will be implemented by a class that represents a
Implementing Shopping Cart
We will create in all four classes that implement IShoppingCart interface:
The first three class contain implementation of IShoppingCart interface for
cookies, session variables and database respectively. The last class is what we
will be using in our application. This class further wraps previous three
classes. The class has a constructor that accepts the cart type - Cookie,
Session or Database. Depending on the supplied type it creates an instance of
CCookieShoppingCart or CSessionShoppingCart or CDatabaseShoppingCart.
Complete source code of this implementation is available along with this
article (please see top right corner).