在 Bash 中完成一些常见的设计模式

Section 65.1: 发布/订阅(Pub/Sub)模式

当 Bash 项目变成一个库时,添加新功能就会变得很困难。函数名、变量和参数通常需要在使用它们的脚本中进行修改。在这种情况下,解耦代码并使用事件驱动设计模式会很有帮助。在上述模式中,外部脚本可以订阅一个事件。当事件被触发(发布)时,脚本就可以执行它在事件中注册的代码。

pubsub.sh:

\#!/usr/bin/env bash

#
# Save the path to this script's directory in a global env variable
#
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

#
# Array that will contain all registered events
#
EVENTS=()

function action1() {
    echo "Action #1 was performed ${2}"
}

function action2() {
    echo "Action #2 was performed"
}

#
# @desc :: Registers an event
# @param :: string $1 - The name of the event. Basically an alias for a function name
# @param :: string $2 - The name of the function to be called
# @param :: string $3 - Full path to script that includes the function being called
#
function subscribe() {
    EVENTS+=("${1};${2};${3}")
}

#
# @desc :: Public an event
# @param :: string $1 - The name of the event being published
#
function publish() {
    for event in ${EVENTS[@]}; do
        local IFS=";"
        read -r -a event <<< "$event"
        if [[ "${event[0]}" == "${1}" ]]; then
        ${event[1]} "$@"
        fi
    done
}

#
# Register our events and the functions that handle them
#
subscribe "/do/work" "action1" "${DIR}"
subscribe "/do/more/work" "action2" "${DIR}"
subscribe "/do/even/more/work" "action1" "${DIR}"

#
# Execute our events
#
publish "/do/work"
publish "/do/more/work"
publish "/do/even/more/work" "again"

用下面的方式运行:

chmod +x pubsub.sh
./pubsub.sh