POEAA系列

POEAA(Patterns of Enterprise Application Architecture)中的Transaction Script是一种软体设计模式,其主要特点是透过将每个业务交易与一个脚本(script)相关联,来组织应用程式的业务逻辑。在这个模式中,每个交易通常被实现为一个独立的程式或方法,负责处理该特定交易的逻辑。

Transaction Script 主要特点:

每个交易都有对应的脚本: 每个业务交易都有自己的脚本或类别,其中包含执行该交易所需的逻辑。脚本的目的是将每个交易的逻辑保持在一个地方,以便更容易管理。

 Transaction Script适用于业务逻辑相对简单,不涉及物件之间复杂交互的情境。

优点

  1. 简单,对大多数开发者都可用理解
  2. 一个事务的处理,不会影响到其他的事务

缺点

当业务逻辑复杂时,系统每增加一个业务流程,程式码就会增加一个或几个方法,最后业务类别中存在大量相似的程式码(重用性不强,难以维护)

以下的例子是以一个银行转帐的情境用BankTranferScript类别来表示出银行转帐交易脚本。

using System;

// Transaction Script for handling a bank transfer
public class BankTransferScript
{
    private int sourceAccountId;
    private int targetAccountId;
    private decimal amount;

    // Constructor to initialize input parameters
    public BankTransferScript(int sourceAccountId, int targetAccountId, decimal amount)
    {
        this.sourceAccountId = sourceAccountId;
        this.targetAccountId = targetAccountId;
        this.amount = amount;
    }

    // Method to process the bank transfer
    public void ProcessTransfer()
    {
        // Check if the source account has sufficient balance
        decimal sourceBalance = GetAccountBalance(sourceAccountId);
        if (sourceBalance >= amount)
        {
            // Deduct amount from the source account
            UpdateAccountBalance(sourceAccountId, sourceBalance - amount);

            // Add amount to the target account
            decimal targetBalance = GetAccountBalance(targetAccountId);
            UpdateAccountBalance(targetAccountId, targetBalance + amount);

            Console.WriteLine($"Transfer successful: ${amount} transferred from Account {sourceAccountId} to Account {targetAccountId}");
        }
        else
        {
            Console.WriteLine("Transfer failed: Insufficient balance in the source account.");
        }
    }

    // Method to retrieve account balance (not implemented in this example)
    private decimal GetAccountBalance(int accountId)
    {
        // Placeholder for retrieving account balance from a database or other source
        // (Not implemented in this example)
        return 1000; // Default balance for the sake of the example
    }

    // Method to update account balance (not implemented in this example)
    private void UpdateAccountBalance(int accountId, decimal newBalance)
    {
        // Placeholder for updating account balance in a database or other source
        // (Not implemented in this example)
        Console.WriteLine($"Account {accountId} balance updated to ${newBalance}");
    }
}

class Program
{
    static void Main()
    {
        // Example usage of the BankTransferScript
        BankTransferScript transferScript = new BankTransferScript(sourceAccountId: 1, targetAccountId: 2, amount: 500);
        transferScript.ProcessTransfer();
    }
}

老E随手写