mit*_*esh 3 javascript design-patterns
我有一个关于书中命令模式解释的问题- 由 addy osmani 编写的基本 js 设计模式。
(function(){
var carManager = {
// request information
requestInfo: function( model, id ){
return "The information for " + model + " with ID " + id + " is foobar";
},
// purchase the car
buyVehicle: function( model, id ){
return "You have successfully purchased Item " + id + ", a " + model;
},
// arrange a viewing
arrangeViewing: function( model, id ){
return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
}
/* The function that acts as a common point for function calls */
execute : function ( name ) {
return carManager[name] && carManager[name].apply( carManager, [].slice.call(arguments, 1) );
};
};
})();
Run Code Online (Sandbox Code Playgroud)
以上是作为模式解释的一部分的代码。它将使执行作为模块的单个入口点,该模块将根据传递给它的参数调用适当的方法。
carManager.execute( "arrangeViewing", "Ferrari", "14523" );
carManager.execute( "requestInfo", "Ford Mondeo", "54323" );
carManager.execute( "requestInfo", "Ford Escort", "34232" );
carManager.execute( "buyVehicle", "Ford Escort", "34232" );
Run Code Online (Sandbox Code Playgroud)
引用本书:
如果 carManager 背后的核心 API 发生了变化。这将要求在我们的应用程序中直接访问这些方法的所有对象也被修改。这可以被视为耦合层,它有效地违背了尽可能松散耦合对象的 OOP 方法。相反,我们可以通过进一步抽象 API 来解决这个问题。
根据上述优点,execute方法是作为其一部分添加的层。但是正如您所看到的,即使是这个附加抽象层的实现也需要更改模块外的方法调用,因为第一个参数是指被调用的函数名称。
假设,模块的一个内部函数从“arrangeViewing”变为“arrangeViewing2”,这将需要该模块的所有依赖代码从
carManager.execute( "arrangeViewing", "Ferrari", "14523" );
Run Code Online (Sandbox Code Playgroud)
到
carManager.execute( "arrangeViewing2", "Ferrari", "14523" );
Run Code Online (Sandbox Code Playgroud)
除非我们不在执行函数代码中使用映射,该映射将函数标签指向内部的实际函数。那么上面的代码示例中提到的优势不是毫无意义吗?
同样根据上面引用的书中的这段代码,我们不会将carManager其他模块释放到外部范围以使其能够使用它。此外,如果我们将 execute 作为单一入口点,为什么其他函数不能是私有的?
我的观点是正确的还是我遗漏了什么重要的东西?请帮帮我。
在 Java、c++、c# 等静态类型语言中,通过命令模式解耦是必不可少的。但是在像 JavaScript 这样的动态类型语言中它不是那么重要,因为我们可以非常自由地传递任何方法。所以我也没有看到这方面的优势。
但是 Command 具有书中没有提到的其他特性,例如 Command 可以作为系统中动作的单一事实来源,我们可以记录系统中发生的事情,我们可以为优雅的回滚机制创造可能性,创建如果需要,请排队等待命令等。
顺便说一下,整个 Redux 架构实际上是命令模式,其中:
The Store = The Receiver
The Action = The Command
Dispatch = Executor
Run Code Online (Sandbox Code Playgroud)
PS 我发现在 GoF 书上阅读 Addy 的书很有用。
| 归档时间: |
|
| 查看次数: |
1362 次 |
| 最近记录: |