简体   繁体   中英

Simple Factory Pattern in C#

I am trying to create a simple factory pattern. Below is my sample code:

IMobile:

namespace SimpleFactory
{
public interface IMobile
{
 void Hello();
}
}

IPhone:

namespace SimpleFactory
{
public class Iphone : IMobile
{
    public void Hello()
    {
        Console.WriteLine("Hello, I am Iphone!");
    }
}
}

Nokia

namespace SimpleFactory
{
public class Nokia : IMobile
{
    public void Hello()
    {
        Console.WriteLine("Hello, I am Nokia!");
    }
}
public void NokiaClassOwnMethod()
    {
        Console.WriteLine("Hello, I am a Nokia class method. Can you use me 
with Interface");
    }
}

MobileFactory:

namespace SimpleFactory
{
public class MobileFactory
{
    public IMobile GetMobile(string mobileType)
    {
        switch (mobileType)
        {
            case "Nokia":
                return new Nokia();
            case "iPhone":
                return new Iphone();
            default:
                throw new NotImplementedException();
        }
    }
}
}

Program:

namespace SimpleFactory
{
class Program
{
    static void Main(string[] args)
    {
        MobileFactory factory = new MobileFactory();
        IMobile mobile = factory.GetMobile("Nokia");
        mobile.Hello(); 
        mobile.NokiaClassOwnMethod();


    }
}
}

I would like to access NokiaClassOwnMethod method of the Nokia and Iphone. Can I access NokiaClassOwnMethod method of the Nokia or Iphone class. If not, why? (I can add this NokiaClassOwnMethod method to the Interface and able to access it. But my question is How I can access class own methods? )

In order to do that you will need to add Hello method to your interface:

public interface IMobile
{
   void Hello();
}

It was not accessible previously because your factory method returned an interface and interface did not contain Hello() method. So during the runtime different types can be returned and when you call Hello child specific class implementation will be called. If you want to have access to method/property that doesn't exist in interface but in the concrete implementation, you will need to cast:

MobileFactory factory = new MobileFactory();
IMobile mobile = factory.GetMobile("Nokia");
var iPhone = mobile as Iphone;
if(iPhone != null) iPhone.Hello();

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