2

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
  • Thing to note about interfaces in .NET: They can be used as object types. So if Two random objects (Car and Telephone) both implement the interface ILike, you can have a function return either types by specifying ILike as the return type of the function. Commented Nov 12, 2009 at 20:51

3 Answers 3

7

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;
         }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.