Tuesday, December 9, 2008

Dish #2: A generic AbstractFactory class

#region Copyright
///Copyright 2008 Codesagar.
///DISCLAIMER: Author claims no responsibility for any damages whatsoever
///stemming out either directly or indirectly from the usage of any of the
///source code made available through Codesagar.
#endregion

using
System;

namespace Factories
{
   
/// <summary>
   /// Usage: TConcreteFactory is the concrete factory that implements this base
    /// class and creates instances of type TCreatedType (and its derived classes)
   /// </summary>
   /// <typeparam name="TConcreteFactory">Concrete factory type</typeparam>
   /// <typeparam name="TProduct">Product type to be created by the
    /// concrete factory
   /// </typeparam>
   public class AbstractFactory<TConcreteFactory, TProduct> :
       
SingletonBase<TConcreteFactory>
        
where TConcreteFactory : class, new()
       
where TProduct : class
   {
       
/// <summary>
       /// This is the factory class that must be implemented by your concrete
        /// factory instance.
       /// </summary>
       /// <param name="args">Arguments that your implementation of Create
        /// can accept.
       /// </param>
       /// <returns>Return the instance of your desired type TProduct or its
        /// subtype
       /// </returns>
       public virtual TProduct Create(params object[] args)
       {
           
throw new NotImplementedException();
       }
   }

   
class ExampleProduct { }
   
class ExampleFactory : AbstractFactory<ExampleFactory, ExampleFactory>
   {
       
public override ExampleFactory Create(params object[] args)
       {
           
return new ExampleFactory();
       }
   }

   
class ExampleClient
   {
       
public void Demonstrate()
       {
           
ExampleFactory.Instance.Create();
       }
   }

}


No comments: