/**
+ Request information about the car
+ @param model - model of car
+ @param id - id of car
**/
function requestInfo(model, id) {
return `${model} with id: ${id}`
}
/**
+ Buy the car
+ @param model - model of car
+ @param id - id of car
**/
function buyVehicle(model, id) {
return `You purchased ${model} with id: ${id}`
}
/**
+ Arrange viewing for car
+ @param model - model of car
+ @param id - id of car
**/
function arrangeViewing(model, id) {
return `You have successfully booked a viewing of ${model} (${id})`
}
/**
+ A generic execute function
+ Takes a receiver and a command
**/
export default function execute(receiver, command) {
return receiver[command.action] && receiver[command.action](...command.params)
}
现在我们无论在何时何地都可以执行这些命令了。
Make things happen | 让奇迹发生
import execute from 'executor.js'
import TeslaSalesControl from 'receiver.js'
// Arrange a viewing
execute(TeslaSalesControl, {
action: 'arrangeViewing',
param: ['Model S', '123'],
})
// Request Info
execute(TeslaSalesControl, {
action: 'requestInfo',
param: ['Model S Battery', '123342'],
})
// Buy a Car!
execute(TeslaSalesControl, {
action: 'buyVehicle',
param: ['Tesla 3', '23243425'],
})
就是这样,现在让我们来对比一下 Redux!在 Redux 中:
The Store = The Receiver | Store 即接收器
Store 会根据 “reducers” 进行初始化,描述 Store 是如何变化的。这些 reducers 都是一些纯函数,每当被调用的时候都会返回一个新的 state,而不会导致莫名其妙地发生变化。这使得我们的代码具有高度的可预测性以及可测试性。
import { combineReducers } = 'redux';
function arrangeViewing(state, action) {
switch(action.type) {
case "ARRANGE_VIEWING":
const { model, id } = action.data;
return `${model} and ${id}`
default:
return ""
}
}
function requestInfo(state, action) {
switch(action.type) {
case "REQUEST_INFO":
const { model, id } = action.data;
return `${model} and ${id}`
default:
return ""
}
}
function buyVehicle(state, action) {
switch(action.type) {
case "BUY_VEHICLE":
const { model, id } = action.data;
return `${model} and ${id}`
default:
return false
}
}
const rootReducer = combineReducers({
arrangeViewing,
requestInfo,
buyVehicle
});
export default rootReducer;
import { applyMiddleware, createStore } from 'redux'
import createLogger from 'redux-logger'
import ReduxThunk from 'redux-thunk'
import rootReducer from '../imports/client/reducers/rootReducer'
// create a logger
const logger = createLogger()
const middleware = [ReduxThunk, logger]
const Store = createStore(rootReducer, {}, applyMiddleware(...middleware))
export default Store
对于设计模式我们可以追溯到 Christopher Alexander, (中译名:)的作者,Alexander 意识到,随着时间的推移,某些方法所创造的结构可以达成效率。当时,由于 Alexander 的工作,其他出版物也开始出来了。其中很棒的一本读物就是 (中译名:)。这本书描述了给常见的软件开发问题提供解决方案的各种模式。