这似乎是一种合理的方法。您不想使用太多静态类/方法的原因是,您最终将从面向对象编程转向更多的结构化编程领域。
在您只是将A转换为B的情况下,假设我们所做的只是将文本转换为
代码语言:javascript运行复制"hello" =>(transform)=> "Hello!"那么静态方法就有意义了。
然而,如果你经常在一个对象上调用这些静态方法,并且它在很多调用中都是唯一的(例如,你使用它的方式取决于输入),或者它是对象固有行为的一部分,那么明智的做法是让它成为对象的一部分,并维护它的一个状态。要做到这一点,一种方法是将其实现为接口。
代码语言:javascript运行复制class Interface{
method toHtml(){
return transformed string (e.g. "Hello!")
}
method toConsole(){
return transformed string (e.g. "printf Hello!")
}
}
class Object implements Interface {
mystring = "hello"
//the implementations of the interface would yield the necessary
//functionality, and it is reusable across the board since it
//is an interface so... you can make it specific to the object
method toHtml()
method toConsole()
}编辑:大量使用静态方法的一个很好的例子是Asp.Net、MVC或Ruby中的html helper方法。它们创建的html元素与对象的行为无关,因此是静态的。
编辑2:将函数式编程改为结构化编程(由于某种原因,我感到困惑),支持Torsten指出这一点。