Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Design Pattern for the Following Scenario

I'm trying to improve my coding style. Consider the following scenario:
Suppose that I want define a custom ASP.Net Album server control. The purpose is to let the user choose the album type and all other stuff will be carried out by the control.
I have thought about 2 approaches:

1- Define an IAlbum Interface and define a class (which implements IAlbum) for every Album type. For example:

  public class FlashAlbum : IAlbum  
  {  
  // Implement IAlbum Methods...  
  // FlashAlbum-Specific Properties/Methods.  
  }  
  public class JSAlbum : IAlbum  
  {  
  // Implement IAlbum Methods...   
  // JSAlbum-Specific Properties/Methods.  
  }  

So if the user wants a flash album, he should explicitly create a FlashAlbum Object. something like:

var myFlashAlbum = new FlashAlbum(/*FlashAlbumParameters*/);  
var myJSAlbum = new JSAlbum(/*JSAlbumParameters*/);  

The problem is that I don't want the user to have to deal with multiple album types. Read below to understand what I mean.

2- Define IAlbum, define a class (which implements IAlbum) for every Album type (just like above) and define Album class which does not implement IAlbum. It is used to create album instances in its contructor (factory pattern). Define EnumAlbumTypes:

Public Enum AlbumTypes  
{  
    FlashAlbum,  
    JSAlbum  
}  

Now define a constructor for the Album Parent class that takes the a parameter of type EnumAlbumTypes and creates the appropriate album based on the parameter. I prefer this method. But I'm not very familiar with factory pattern. I want the user to create albums like:

var myFlashAlbum = new Album(AlbumTypes.FlashAlbum);  
// Now set FlashAlbum custom properties.
var myJSAlbum = new Album(AlbumTypes.JSAlbum);
// Now set JSAlbum custom properties.  

What is the best approach to achieve this?
Thanks and sorry for the long post.

like image 662
Kamyar Avatar asked Nov 13 '10 11:11

Kamyar


1 Answers

The Factory pattern is a good option when you want to encapsulate the decision about the specific type of object to create. The create method should return an Album type so it will be:

   var myFlashAlbum = Album.create(AlbumTypes.FlashAlbum);
   var myJSAlbum = Album.create(AlbumTypes.JSALbum);

If the process of constructing the albums are significantly different you may want to consider the builder pattern. It allows you to encapsulate the complex create logic.

like image 196
Vincent Ramdhanie Avatar answered Nov 13 '22 05:11

Vincent Ramdhanie