Bill Martin
Bill Martin

Reputation: 4943

How to return an object that implements an interface from a method

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.

Upvotes: 2

Views: 4217

Answers (3)

Marcel Gosselin
Marcel Gosselin

Reputation: 4716

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;
         }
     }
}

Upvotes: 7

qid
qid

Reputation: 1913

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();
}

Upvotes: 0

kemiller2002
kemiller2002

Reputation: 115488

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();

Upvotes: 1

Related Questions