我现在在课程设计上有问题了。问题如下:
我想设计水果和榨汁机的课程。水果的课程(苹果,梨,桃子)都完成了。现在我想为榨汁机设计课程。
对榨汁机的要求是:
1.榨汁机以特定的水果(苹果、梨、桃子)为原料生产果汁。注:可能有混合果汁(如苹果和梨的味道)。
2.一种榨汁机只能生产一种果汁。
3.榨汁机有存放水果的空间,我们可以知道还有多少苹果或梨还在那里。(我们假设每次一个榨汁机使用一个苹果或梨)。
有人能给我一些建议吗?
发布于 2015-09-17 07:16:10
马克的回答很好而且是个好的开端..。我会扩大一点。我可能不会使用数组的水果,因为你将添加,删除等.使用列表或类似的方法可能更容易实现。此外,莱恩说,他想要多个水果在一些果汁。这会使事情变得复杂一些,让我们做出一些决定。
如果它总是最多两个水果,我可能只会做两个果汁类,类似于Mark的答案:
public interface IFruit
{
string Name {get;}
}
public class Apple : IFruit
{
public string Name { get {return "Apple";} }
}
public class Pear : IFruit
{
public string Name { get {return "Pear";} }
}
public class Juicer<IFruit>
{
private IList<IFruit> fruits;
public Juicer(IList<IFruit> fruits)
{
this.fruits = fruits;
}
public int FruitCount
{
get { return this.fruits.Count; }
}
// Other members can go here...
}
public class TwoFruitJuicer<IFruit, IFruit2>
{
private IList<IFruit> fruits;
private IList<IFruit2> fruits2;
public TwoFruitJuicer(IList<IFruit> fruits, IList<IFruit2> fruits2)
{
this.fruits = fruits;
this.fruits2 = fruits2;
}
public int FruitCount
{
get { return this.fruits.Count + this.fruits2.Count; }
}
// Other members can go here...
}但是,假设你想要3到4种不同的果汁加在一起.
public class MulitJuicer
{
private IList<Juicer<IFruit>> _juicers;
public MulitJuicer(IList<Juicer<IFruit>> juicers)
{
this._juicers = juicers;
}
public int FruitCount
{
get {
int allFruitCount = 0;
foreach (var j in _juicers)
{
allFruitCount += j.FruitCount;
}
return allFruitCount;
}
}
}然而,这可能是相当困难的使用,在列表中的许多列表,以跟踪建立和诸如此类的.如果你只需要一次榨汁机就能把一堆水果倒进去怎么办?我们可以使用反射来验证只有允许的水果被放入榨汁机:
public class MultiFruitJuicer
{
private IList<Type> _juiceTypes;
private IList<IFruit> _fruits;
public MultiFruitJuicer(IList<Type> juiceTypes, IList<IFruit> fruits)
{
_juiceTypes = juiceTypes;
_fruits = fruits;
if (!ValidateFruits())
{
//you may not want to actually throw here...
throw new Exception("Not all proper fruit types");
}
}
public bool ValidateFruits()
{
//there are about a million ways to do this... this is probably not the best...
foreach(var f in _fruits)
{
if (!_juiceTypes.Contains(f.GetType()))
{
return false;
}
}
return true;
}
public int FruitCount
{
get { return this._fruits.Count; }
}
}发布于 2015-09-17 06:13:17
如果您的语言支持仿制药 (就像C#和Java一样),最简单的解决方案将是使Juicer更通用:
public class Juicer<T>
{
private T[] fruits;
public Juicer(T[] fruits)
{
this.fruits = fruits;
}
public FruitCount
{
get { return this.fruits.Length; }
}
// Other members can go here...
}您可以创建一个对象,即Juicer<Apple>,另一个对象为Juicer<Pear>,依此类推。Juicer<Apple>只能包含Apple对象等。
发布于 2015-09-17 05:32:56
首先,我将为
榨汁机设计课
它将帮助您构造一个复杂的对象(果汁)并分离它的表示,这样相同的构造过程就可以创建不同的表示(各种果汁)。
添加一些接口(IFruit)和基类(重量、大小等共享代码)至
水果类(苹果、梨、桃)
每台榨汁机都有
ICollection<IFruit> fruits这是可以管理的- .Count(),.Add(IFruit)或.Remove(IFruit)。
https://stackoverflow.com/questions/32621336
复制相似问题