继承抽象类 - 选择模式

Gri*_*ela 2 .net c# asp.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;
    }


}
Run Code Online (Sandbox Code Playgroud)

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

Tomato:Ingredient {//implementation}
Cheese:Ingredient {//implementation}
Mushrooms:Ingredient {//implementation}
Onion:Ingredient {//implementation}
Run Code Online (Sandbox Code Playgroud)

但我想我的成分,有一些类型的测量可以decimal Quantity或者int 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; }
}
Run Code Online (Sandbox Code Playgroud)

但类不能有两个基类.(我不能Tomato:Ingredient, Countable {//implementation})我不能使用接口,因为我希望我的测量只对子元素可见,我想封装测量(所以当我想改变一些基础时例如,Countable中的逻辑我不必更改每个子实现)

Mig*_*oom 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; }
}
Run Code Online (Sandbox Code Playgroud)

所以那些来自CountableQantable将来的类Ingredient也是如此.