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.


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.


If you don't want the user to care about what kind of album they have, then why are you even giving them the choice?

Inheritance seems to be the right choice here. I don't see any evidence or arguments in favour of the other option.

链接地址: http://www.djcxy.com/p/48858.html

上一篇: GLSL可以同时输出两个/多个纹理吗?

下一篇: 以下情景的最佳设计模式