C#Factory Pattern - 将始终调用Base方法

时间:2014-07-25 14:11:37

标签: c# design-patterns

我想知道为什么在下面的示例中,即使我在工厂模式"构建器"时覆盖它,也始终会调用基本方法。返回对象的新实例?

interface FactoryInter 
{
    void MakeDetails();

}

class Builder {

    public static Builder getObject(string obj)
    {
        if(obj == "Cont")
        {
            return new Cont();
        }else{
            return new Builder();
        }

    }

    public void MakeDetails()
    {
        Console.WriteLine("I will always get called..");
    }

}

class Cont : Builder, FactoryInter {

    public void MakeDetails()
    {
        Console.WriteLine("Hello..");
    }

}

public class Test
{
    public static void Main()
    {
        Builder b = new Builder();
        b = Builder.getObject("Cont");

        b.MakeDetails();
        // your code goes here
    }
}

非常感谢任何帮助

1 个答案:

答案 0 :(得分:7)

你不要覆盖它。你在隐藏它。方法Cont.MakeDetails()隐藏了基类的MakeDetails方法。有关详细信息,请参阅以下示例:

class Base
{
    public void Hidden()
    {
        Console.WriteLine("Base!");
    }

    public virtual void Overrideable()
    {
        Console.WriteLine("Overridable BASE.");
    }
}

class Derived : Base
{
    public void Hidden()
    {
        Console.WriteLine("Derived");
    }

    public override void Overrideable()
    {
        Console.WriteLine("Overrideable DERIVED");
    }
}

现在测试它们会产生以下结果:

var bas = new Base();
var der = new Derived();

bas.Hidden(); //This outputs Base!
der.Hidden(); //This outputs Derived
((Base)der).Hidden(); 
//The above outputs Base! because you are essentially referencing the hidden method!

//Both the below output Overrideable DERIVED 
der.Overrideable();
((Base)der).Overrideable();

要覆盖它,请将基本方法标记为虚拟,将派生方法标记为覆盖。