Online courses in ASP.NET MVC, ASP.NET Core, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC, ASP.NET Core, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

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, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation 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