簡體   English   中英

不使用virtual關鍵字的多態

[英]Polymorphism without using the virtual keyword

顯然,使用虛擬和替代是正常情況,但是這個電信示例是否有價值?

public class Pipe
{
  // whole bunch of protected member variables such as bandwidth, latency, download limit 
  // etc,

  public int GetCost()
  {
     // work out cost based on above
  }
}

public class BigFatPipe : Pipe
{
  public BigFatPipe()
  {
    // sets up the member variables one way
  }
}

public class CheapestPossiblePipe: Pipe
{
  public CheapestPossiblePipe()
  {
    // sets up the member variables another way
  }
}

那你可能會打電話

PrintPrice(new BigFatPipe())

PrintPrice(new CheapestPossiblePipe())

public void PrintPrice(Pipe pipe)
{
   int a = pipe.GetCost();
   ....
}

您會得到兩個不同的答案。 這不是最有用的示例,但是它有用嗎?

這篇文章對確切的多態性進行了有用的討論。

我認為大多數定義都沒有明確指出對象必須具有多態的虛函數-是的,我認為您的示例很重要。

構造函數重載是實現靜態多態性的公認方法。 盡管這並不是真正的構造函數重載,但已經很接近了。 所以是的,我稱之為多態性。

這種模式確實有效,但是引入一堆類會使用戶無用的困惑:他們會想知道這些類的不同之處。

一些工廠方法可以完成相同的工作,並且更易於理解和維護:

public class Pipe
{
  // whole bunch of private member variables such as bandwidth, latency, download limit 
  // etc,

  public int GetCost()
  {
     // work out cost based on above
  }

  public static Pipe MakeBigFatPipe()
  {
      var result = new Pipe();
      // sets up the member variables one way
      return result;
  }

  public static Pipe MakeCheapestPossiblePipe()
  {
      var result = new Pipe();
      // sets up the member variables another way
      return result;
  }
}

如果我是你,我將使用以下方法:

public interface IGetCost
{
    int GetCost();
}

public class Pipe : IGetCost
{
    public int GetCost(){}
}

public class BigFatPipe : IGetCost
{
    //aggregation
    private readonly Pipe _pipe;

    public BigFatPipe(Pipe pipe)
    {
        _pipe = pipe;
    }
    public int GetCost() { }
}

public class CheapestPossiblePipe : IGetCost
{
    private readonly Pipe _pipe;

    public CheapestPossiblePipe(Pipe pipe)
    {
        _pipe = pipe;
    }
    public int GetCost() { }
}

public static void PrintPrice(IGetCost obj)
{
    int cost = obj.GetCost();
    Console.WriteLine(cost);
}

static void Main(string[] args)
{
    IGetCost p;

    p = new Pipe();
    PrintPrice(p);

    p = new BigFatPipe();
    PrintPrice(p);

    p = new CheapestPossiblePipe();
    PrintPrice(p);
}

我還需要說的是,有兩種不同的東西-多態和重載

多態性

public class foo
{
    public virtual void foo1{/*....*/}
}

public class fooA : foo
{
    public override void foo1{/*....*/}
}

public class fooB : foo
{
    public new void foo1{/*....*/}
}

public class fooC : foo
{
    //new is the default modifier
    public void foo1{/*....*/}
}

超載

public class foo{
    public int foo1{/*....*/}
    public int foo1(int a){/*....*/}
    public int foo1(string a){/*....*/}
    public int foo1(int a, string b){/*....*/}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM