samedi 29 février 2020

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

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!");
    }
}
}

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(); // Not able to access Hello method of Nokia class.           
    }
}
}

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

Aucun commentaire:

Enregistrer un commentaire