Enterprise Architecture
POEAA(Patterns of Enterprise Application Architecture)中的Transaction Script是一種軟體設計模式,其主要特點是透過將每個業務交易與一個腳本(script)相關聯,來組織應用程式的業務邏輯。在這個模式中,每個交易通常被實現為一個獨立的程式或方法,負責處理該特定交易的邏輯。
Transaction Script 主要特點:
每個交易都有對應的腳本: 每個業務交易都有自己的腳本或類別,其中包含執行該交易所需的邏輯。腳本的目的是將每個交易的邏輯保持在一個地方,以便更容易管理。
Transaction Script適用於業務邏輯相對簡單,不涉及物件之間複雜交互的情境。
優點
- 簡單,對大多數開發者都可用理解
- 一個事務的處理,不會影響到其他的事務
缺點
當業務邏輯複雜時,系統每增加一個業務流程,程式碼就會增加一個或幾個方法,最後業務類別中存在大量相似的程式碼(重用性不強,難以維護)
以下的例子是以一個銀行轉帳的情境用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();
}
}
元哥的筆記