场景:我在类字段中存储了一些信息(例如,双精度数组)(比如字段Measurements,类中的整数数组MeasureData).现在我想使用这些数据来执行一些计算(例如,计算数组的算术平均值,最大值和最小值).此刻,我不知道在未来,我需要做的这些数据的任何其它操作(例如,也许我会需要得到标准差,总和或其他).我会有很多类型的对象MeasureData.
解决方案:我可以编写一个类Calculator,声明它是final,使用私有构造函数并使用几个静态方法来执行我需要的计算.这似乎是有道理的,因为它Calculator充当实用类,没有任何字段,就像标准Math类一样.
问题:如果在几个月内我需要进行任何其他计算,我将需要编写另一个静态方法Calculator.这是否意味着违反开放/封闭原则(毕竟,我正在修改类的实现Calculator)?
我是 Rust 的新手,我正在尝试了解该语言的基础知识。
\n\n考虑以下特征
\n\ntrait Function {\n fn value(&self, arg: &[f64]) -> f64;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n和两个实现它的结构:
\n\nstruct Add {}\n\nstruct Multiply {}\n\nimpl Function for Add {\n fn value(&self, arg: &[f64]) -> f64 {\n arg[0] + arg[1]\n }\n}\n\nimpl Function for Multiply {\n fn value(&self, arg: &[f64]) -> f64 {\n arg[0] * arg[1]\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n在我的main()函数中,我想将Add\xc2\xa0and的两个实例分组Multiply到一个向量中,然后调用该value方法。以下作品:
fn main() {\n let x = vec![1.0, 2.0];\n let funcs: Vec<&dyn Function> = vec![&Add {}, &Multiply …Run Code Online (Sandbox Code Playgroud) 考虑以下情况:
public abstract class AnimalFeed{
}
public class FishFeed extends AnimalFeed{
}
public class BirdFeed extends AnimalFeed{
}
public abstract class Animal{
public void eat(AnimalFeed somethingToEat)
}
Run Code Online (Sandbox Code Playgroud)
现在我想定义一个扩展"动物"的类"鸟",确保当它吃鸟时,它只吃BirdFeed.
一种解决方案是指定一种合同,其中"eat"的调用者必须传递适当的feed的实例
public class Bird extends Animal{
@Override
public void eat(AnimalFeed somethingToEat){
BirdFeed somethingGoodForABird
if(somethingToEat.instanceOf(BirdFeed)){
somethingGoodForABird = (BirdFeed) somethingGoodForABird
}else{
//throws error, complaining the caller didn't feed the bird properly
}
}
}
Run Code Online (Sandbox Code Playgroud)
将参数的责任委托给调用者是否可以接受?如何强制调用者传递参数的特化?有替代设计解决方案吗?
java ×2
polymorphism ×2
actor-model ×1
asynchronous ×1
dispatch ×1
inheritance ×1
oop ×1
pykka ×1
python ×1
rust ×1
traits ×1