简体   繁体   English

C#中的简单工厂模式

[英]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.我想访问诺基亚和 Iphone 的 NokiaClassOwnMethod 方法。 Can I access NokiaClassOwnMethod method of the Nokia or Iphone class.我可以访问诺基亚或 Ip​​hone 类的 NokiaClassOwnMethod 方法吗? 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? ) (我可以将此 NokiaClassOwnMethod 方法添加到接口并能够访问它。但我的问题是如何访问类自己的方法?)

In order to do that you will need to add Hello method to your interface:为此,您需要将Hello方法添加到您的界面:

public interface IMobile
{
   void Hello();
}

It was not accessible previously because your factory method returned an interface and interface did not contain Hello() method.以前无法访问它,因为您的工厂方法返回了一个接口,而该接口不包含Hello()方法。 So during the runtime different types can be returned and when you call Hello child specific class implementation will be called.因此在运行时可以返回不同的类型,并且当您调用Hello子特定类实现时将被调用。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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