继承抽象类 - 选择模式

时间:2017-03-24 13:53:25

标签: c# asp.net .net

我有抽象类:

public abstract class Ingredient 
{
    private string name;
    private decimal price;

    public Ingredient(string name, decimal price)
    {
        this.name = name;
        this.price = price;
    }

    public string Name
    {
        get
        {
            return this.name;
        }
    }

    protected decimal Price
    {
        get
        {
            return this.price;
        }
    }

    protected void ChangePrice(decimal newPrice)
    {
        Console.WriteLine(string.Format("The price changed from {0} to {1} for engridient {2}", this.price, newPrice,this.name));
        this.price = newPrice;
    }


}

然后我有很多成分继承了成分:

Tomato:Ingredient {//implementation}
Cheese:Ingredient {//implementation}
Mushrooms:Ingredient {//implementation}
Onion:Ingredient {//implementation}

但是我希望我的成分能够根据成分的类型进行某种类型的测量,可以是decimal Quantityint Count。例如,番茄是可数的(3个西红柿),奶酪是通过decimal Quantity(30克奶酪)来测量的。我试着制作抽象类:

public abstract class Countable
{
   protected abstract int Count { get; set; }
}

public abstract class Qantable
{
    protected abstract decimal Quantity { get; set; }
}

但是类不能有两个基类。(我不能有Tomato:Ingredient, Countable {//implementation})我不能使用接口,因为我希望我的测量仅对子元素可见,我想封装测量(因此,当我想在Countable中更改一些基本逻辑时,我不必更改每个子实现)

1 个答案:

答案 0 :(得分:6)

要实现这一目标,您CountableQantable必须来自Ingredient

public abstract class Countable : Ingredient 
{
   protected abstract int Count { get; set; }
}

public abstract class Qantable : Ingredient 
{
    protected abstract decimal Quantity { get; set; }
}

因此,源自CountableQantable的类也将是Ingredient

相关问题