October 2017 : Online course in ASP.NET MVC / Core. Conducted by Bipin Joshi. Read more...
Registration for October 2017 batch of ASP.NET MVC / Core online course has already started. Conducted by Bipin Joshi. Book your seat today ! Click here for more details.

Developing a Shopping Cart - Part 4

Introduction

In Part1, 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
{
	int ProductID
	{
		get;
		set;
	}
	string ProductName
	{
		get;
		set;
	}
	decimal UnitPrice
	{
		get;
		set;
	}
	int Quantity
	{
		get;
		set;
	}
}

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 shopping cart.

Implementing Shopping Cart

We will create in all four classes that implement IShoppingCart interface:

  • CCookieShoppingCart
  • CSessionShoppingCart
  • CDatabaseShoppingCart
  • CShoppingCart

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.

Code Download

Complete source code of this implementation is available along with this article (please see top right corner).

 


Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 08 May 2005


Tags : ASP.NET Web Forms Server Controls