设计模式对于组织大量代码非常有用。因为您不需要像在 #{verbose_algol_derivitive_language} 中那样编写那么多代码来在 ruby 中执行操作,因此它们的重要性不一样。
您将看到使用什么all时间是用块实现的策略和构建器(构建器的一个例子是 Rails 视图中的 form_for 块,策略的一个例子是 File.open)我真的记不起上次看到任何其他模式是什么时候了(无论如何,gof 模式)
编辑:回应
你的意思是用红宝石我们不需要
考虑大多数的设计模式
案例?另一个问题,如果我使用
Rails,我真的需要考虑吗
关于设计模式?因为我不
知道在哪里使用它们。他们不
似乎适合任何组件
MVC。设计模式仅用于
正在大规模建设的人们
库/框架例如。导轨,
DataMapper、MongoID 等,不适用于
其他人只使用这些
框架/库?
在大多数情况下,rails 会为您做出很多决定,直到您的应用程序达到相当高的复杂程度为止。即使您使用的是 sinatra 之类的东西(它不会为您决定任何事情),您仍然不需要像在(例如)java这样的语言中那样接触这些 GoF 模式。
这是因为设计模式的全部要点是保持事物灵活性和可维护性的封装方法。如果这是内置于语言中的,通常甚至不需要它们。
例如,用 java 实现的策略模式看起来有点像这样
//StrategyExample test application
class StrategyExample {
public static void main(String[] args) {
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3,4);
}
}
// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {
int execute(int a, int b);
}
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyAdd's execute()");
return a + b; // Do an addition with a and b
}
}
class ConcreteStrategySubtract implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategySubtract's execute()");
return a - b; // Do a subtraction with a and b
}
}
class ConcreteStrategyMultiply implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyMultiply's execute()");
return a * b; // Do a multiplication with a and b
}
}
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
private Strategy strategy;
// Constructor
public Context(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
}
这是一项繁重的工作,但你最终得到的东西在很多时候都是值得的,并且可能是一个大泥球和有机会得到维护的东西之间的区别。现在让我们用 ruby 来做
class Context
def initialize(&strategy)
@strategy = strategy
end
def execute
@strategy.call
end
end
a = Context.new { puts 'Doing the task the normal way' }
a.execute #=> Doing the task the normal way
b = Context.new { puts 'Doing the task alternatively' }
b.execute #=> Doing the task alternatively
c = Context.new { puts 'Doing the task even more alternatively' }
c.execute #=> Doing the task even more alternatively
甚至很难称其为模式,您只是在使用块!当语言涵盖了模式所解决的需求时,有效地使用该语言将意味着在大多数情况下您并不真正需要该模式。这也意味着您可以优雅地解决此类问题,而采用 Java 风格的策略可能会造成可怕的矫枉过正。