tags:

views:

192

answers:

3

I'm trying to learn interfaces and want to try the following:

Let's say I have an interface named ICustomer that defines basic properties (UserID, UserName, etc). Now, I have multiple concrete classes like ProductA_User, ProductB_User, ProductC_User. Each one has different properties but they all implement ICustomer as they are all customers.

I want to invoke a shared method in a factory class named MemberFactory and tell it to new me up a user and I just give it a param of the enum value of which one I want. Since each concrete class is different but implements ICustomer, I should be able to return an instance that implements ICustomer. However, I'm not exactly sure how to do it in the factory class as my return type is ICustomer.

+1  A: 

When you call the method all you have to do is return the object as normal. It's mapping it to the interface where it comes into play.

ICustomer obj = MemberFactory.ReturnObjectWhichImplementsICustomer();
Kevin
+5  A: 

All you have to do is create your object like this:

class ProductA_User : ICustomer
{
    //... implement ICustomer
}
class ProductB_User : ICustomer
{
    //... implement ICustomer
}
class ProductC_User : ICustomer
{
    //... implement ICustomer
}

class MemberFactory 
{
     ICustomer Create(ProductTypeEnum productType)
     {
         switch(productType)
         {
             case ProductTypeEnum.ProductA: return new ProductA_User();
             case ProductTypeEnum.ProductB: return new ProductB_User();
             case ProductTypeEnum.ProductC: return new ProductC_User();
             default: return null;
         }
     }
}
Marcel Gosselin
Makes sense! Thanks for the help!
asp316
A: 

The factory method would include code that does something roughly like this:

switch (customerType)
{
case CustomerType.A:
   return new ProductA_User();
case CustomerType.B:
   return new ProductB_User();
case CustomerType.C:
   return new ProductC_User();
}
qid