简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM