システム設計で差がつく!Mermaidクラス図・状態図・ERダイアグラム完全ガイド

システム設計の品質は、プロジェクトの成功を左右する重要な要素です。前回までの記事で Mermaid の基本的なダイアグラムについて学習いたしましたが、今回は システム設計の核心となるクラス図・状態図・ER ダイアグラム に焦点を当てます。
これらの設計図をマスターすることで、オブジェクト指向設計の明確化、システムの状態遷移の可視化、データベース構造の最適化が実現できます。保守性の高いシステム構築と、チーム開発での設計品質向上を目指す実践的な内容をお届けいたします。
クラス図(Class Diagram)でシステム設計
クラス図は、オブジェクト指向システムの構造を表現する UML ダイアグラムの中核となるものです。Mermaid では、クラス間の関係性を明確に表現し、システム設計の理解を深めることができます。
クラス定義とアクセス修飾子
基本的なクラス定義
mermaidclassDiagram
class User {
-id: string
-name: string
-email: string
-password: string
+getId(): string
+getName(): string
+setName(name: string)
+validateEmail(): boolean
-hashPassword(): string
}
class Product {
-id: string
-name: string
-price: number
-stock: number
+getId(): string
+getPrice(): number
+updateStock(quantity: number)
+isAvailable(): boolean
}
アクセス修飾子の表現
mermaidclassDiagram
class BankAccount {
-accountNumber: string
-balance: number
#interestRate: number
+owner: string
+deposit(amount: number): void
+withdraw(amount: number): boolean
+getBalance(): number
-calculateInterest(): number
#validateAmount(amount: number): boolean
~getAccountType(): string
}
note for BankAccount "アクセス修飾子:
+ public
- private
# protected
~ package"
継承・実装・関連の表現方法
継承関係
mermaidclassDiagram
class Animal {
-name: string
-age: number
+getName(): string
+makeSound(): void
}
class Dog {
-breed: string
+bark(): void
+fetch(): void
}
class Cat {
-indoor: boolean
+meow(): void
+scratch(): void
}
Animal <|-- Dog
Animal <|-- Cat
インターフェース実装
mermaidclassDiagram
class <<interface>> Drawable {
+draw(): void
+resize(scale: number): void
}
class <<interface>> Movable {
+move(x: number, y: number): void
+getPosition(): Position
}
class Shape {
-x: number
-y: number
-color: string
+getColor(): string
+setColor(color: string): void
}
class Circle {
-radius: number
+getArea(): number
+draw(): void
+resize(scale: number): void
+move(x: number, y: number): void
}
class Rectangle {
-width: number
-height: number
+getArea(): number
+draw(): void
+resize(scale: number): void
}
Drawable <|.. Circle
Movable <|.. Circle
Shape <|-- Circle
Shape <|-- Rectangle
Drawable <|.. Rectangle
関連・集約・合成関係
mermaidclassDiagram
class University {
-name: string
-departments: Department[]
+addDepartment(dept: Department): void
}
class Department {
-name: string
-professors: Professor[]
+addProfessor(prof: Professor): void
}
class Professor {
-name: string
-title: string
+teach(course: Course): void
}
class Course {
-code: string
-name: string
-credits: number
}
class Student {
-studentId: string
-name: string
+enroll(course: Course): void
}
University ||--o{ Department : 構成
Department ||--o{ Professor : 雇用
Professor ||--o{ Course : 担当
Student }o--o{ Course : 履修
UML 準拠の設計図作成
EC サイトのドメインモデル
mermaidclassDiagram
class Customer {
-customerId: string
-name: string
-email: string
-address: Address
-orders: Order[]
+placeOrder(items: CartItem[]): Order
+getOrderHistory(): Order[]
+updateProfile(info: CustomerInfo): void
}
class Order {
-orderId: string
-orderDate: Date
-status: OrderStatus
-items: OrderItem[]
-totalAmount: number
-shippingAddress: Address
+calculateTotal(): number
+updateStatus(status: OrderStatus): void
+addItem(item: OrderItem): void
}
class OrderItem {
-product: Product
-quantity: number
-unitPrice: number
+getSubtotal(): number
}
class Product {
-productId: string
-name: string
-description: string
-price: number
-category: Category
-inventory: Inventory
+isAvailable(): boolean
+updatePrice(newPrice: number): void
}
class Category {
-categoryId: string
-name: string
-parentCategory: Category
-subCategories: Category[]
+addSubCategory(category: Category): void
}
class Inventory {
-productId: string
-quantity: number
-reservedQuantity: number
+reserve(quantity: number): boolean
+release(quantity: number): void
+getAvailableQuantity(): number
}
class Address {
-street: string
-city: string
-postalCode: string
-country: string
+getFullAddress(): string
+validate(): boolean
}
class Payment {
-paymentId: string
-orderId: string
-amount: number
-method: PaymentMethod
-status: PaymentStatus
+process(): boolean
+refund(): boolean
}
Customer ||--o{ Order : 注文
Order ||--o{ OrderItem : 含む
OrderItem }o--|| Product : 商品
Product }o--|| Category : 分類
Product ||--|| Inventory : 在庫
Order ||--|| Payment : 支払い
Customer ||--o{ Address : 住所
Order }o--|| Address : 配送先
オブジェクト指向設計での実践例
MVC アーキテクチャの表現
mermaidclassDiagram
class <<interface>> View {
+render(data: any): void
+handleUserInput(): void
}
class <<interface>> Model {
+getData(): any
+setData(data: any): void
+validate(): boolean
}
class Controller {
-model: Model
-view: View
+handleRequest(request: Request): Response
+updateModel(data: any): void
+updateView(): void
}
class UserController {
-userService: UserService
+createUser(userData: UserData): User
+getUserById(id: string): User
+updateUser(id: string, data: UserData): User
+deleteUser(id: string): boolean
}
class UserModel {
-id: string
-name: string
-email: string
+validate(): boolean
+save(): boolean
+delete(): boolean
}
class UserView {
-template: string
+renderUserList(users: User[]): string
+renderUserForm(): string
+renderUserDetails(user: User): string
}
class UserService {
-repository: UserRepository
+createUser(data: UserData): User
+findUserById(id: string): User
+updateUser(user: User): User
+deleteUser(id: string): boolean
}
class UserRepository {
-database: Database
+save(user: User): boolean
+findById(id: string): User
+findAll(): User[]
+delete(id: string): boolean
}
Controller --> Model : 更新
Controller --> View : 描画指示
View --> Controller : イベント通知
UserController --|> Controller
UserModel ..|> Model
UserView ..|> View
UserController --> UserService : 依存
UserService --> UserRepository : 依存
UserController --> UserModel : 操作
UserController --> UserView : 描画
デザインパターンの実装例
mermaidclassDiagram
%% Singleton Pattern
class DatabaseConnection {
-instance: DatabaseConnection
-connection: Connection
-DatabaseConnection()
+getInstance(): DatabaseConnection
+getConnection(): Connection
+close(): void
}
%% Factory Pattern
class <<interface>> Animal {
+makeSound(): string
}
class Dog {
+makeSound(): string
}
class Cat {
+makeSound(): string
}
class AnimalFactory {
+createAnimal(type: string): Animal
}
%% Observer Pattern
class <<interface>> Observer {
+update(data: any): void
}
class Subject {
-observers: Observer[]
+addObserver(observer: Observer): void
+removeObserver(observer: Observer): void
+notifyObservers(data: any): void
}
class NewsAgency {
-news: string
+setNews(news: string): void
+getNews(): string
}
class NewsChannel {
-name: string
+update(news: string): void
}
%% Strategy Pattern
class <<interface>> PaymentStrategy {
+pay(amount: number): boolean
}
class CreditCardPayment {
-cardNumber: string
-cvv: string
+pay(amount: number): boolean
}
class PayPalPayment {
-email: string
+pay(amount: number): boolean
}
class PaymentContext {
-strategy: PaymentStrategy
+setStrategy(strategy: PaymentStrategy): void
+executePayment(amount: number): boolean
}
%% 関係性の定義
Animal <|.. Dog
Animal <|.. Cat
AnimalFactory --> Animal : creates
Observer <|.. NewsChannel
Subject <|-- NewsAgency
NewsAgency --> Observer : notifies
PaymentStrategy <|.. CreditCardPayment
PaymentStrategy <|.. PayPalPayment
PaymentContext --> PaymentStrategy : uses
状態図(State Diagram)で状態遷移を可視化
状態図は、システムやオブジェクトが取りうる状態とその間の遷移を表現するダイアグラムです。UI/UX フロー、ビジネスプロセス、システムの動作状態を明確に可視化できます。
状態とトランジションの基本記法
基本的な状態図
mermaidstateDiagram-v2
[*] --> 待機中
待機中 --> 処理中 : 開始
処理中 --> 完了 : 成功
処理中 --> エラー : 失敗
完了 --> [*]
エラー --> 待機中 : リトライ
エラー --> [*] : 終了
詳細な状態遷移
mermaidstateDiagram-v2
[*] --> 初期化
初期化 --> 認証待ち : 初期化完了
認証待ち --> 認証中 : ログイン試行
認証中 --> ログイン済み : 認証成功
認証中 --> 認証待ち : 認証失敗
ログイン済み --> データ読み込み中 : データ要求
データ読み込み中 --> データ表示 : 読み込み完了
データ読み込み中 --> エラー表示 : 読み込み失敗
データ表示 --> データ更新中 : 更新要求
データ更新中 --> データ表示 : 更新成功
データ更新中 --> エラー表示 : 更新失敗
エラー表示 --> データ表示 : 再試行
ログイン済み --> [*] : ログアウト
複合状態と並行状態の表現
複合状態(ネストした状態)
mermaidstateDiagram-v2
[*] --> オフライン
オフライン --> オンライン : 接続
state オンライン {
[*] --> アイドル
アイドル --> 同期中 : データ同期開始
同期中 --> アイドル : 同期完了
state 同期中 {
[*] --> アップロード中
アップロード中 --> ダウンロード中 : アップロード完了
ダウンロード中 --> [*] : ダウンロード完了
}
}
オンライン --> オフライン : 切断
オフライン --> [*] : 終了
並行状態
mermaidstateDiagram-v2
[*] --> アプリケーション起動
state アプリケーション起動 {
state "UI処理" as ui
state "バックグラウンド処理" as bg
state ui {
[*] --> UI初期化
UI初期化 --> ユーザー入力待ち
ユーザー入力待ち --> 画面更新中
画面更新中 --> ユーザー入力待ち
}
state bg {
[*] --> サービス初期化
サービス初期化 --> データ監視中
データ監視中 --> データ処理中
データ処理中 --> データ監視中
}
ui --> [*]
bg --> [*]
}
アプリケーション起動 --> [*] : アプリ終了
UI/UX フローやシステム状態の設計
モバイルアプリのユーザーフロー
mermaidstateDiagram-v2
[*] --> スプラッシュ画面
スプラッシュ画面 --> チュートリアル : 初回起動
スプラッシュ画面 --> ログイン画面 : リピーター
チュートリアル --> ログイン画面 : 完了
ログイン画面 --> ログイン中 : ログイン実行
ログイン中 --> ホーム画面 : 成功
ログイン中 --> エラー表示 : 失敗
エラー表示 --> ログイン画面 : 再試行
ホーム画面 --> 商品一覧 : 商品検索
ホーム画面 --> プロフィール : プロフィール選択
ホーム画面 --> カート : カート選択
商品一覧 --> 商品詳細 : 商品選択
商品詳細 --> カート : カートに追加
商品詳細 --> 商品一覧 : 戻る
カート --> 決済画面 : 決済開始
決済画面 --> 決済処理中 : 決済実行
決済処理中 --> 完了画面 : 決済成功
決済処理中 --> エラー画面 : 決済失敗
完了画面 --> ホーム画面 : ホームに戻る
エラー画面 --> 決済画面 : 再試行
プロフィール --> ホーム画面 : 戻る
カート --> ホーム画面 : 戻る
note right of 決済処理中 : タイムアウト処理
note for 完了画面 : 注文確認メール送信
Web アプリケーションの状態管理
mermaidstateDiagram-v2
[*] --> 初期化中
初期化中 --> 認証チェック中 : 初期化完了
認証チェック中 --> 未認証 : トークンなし/無効
認証チェック中 --> 認証済み : 有効なトークン
未認証 --> ログインフォーム表示 : --
ログインフォーム表示 --> ログイン処理中 : ログイン送信
ログイン処理中 --> 認証済み : 認証成功
ログイン処理中 --> ログインエラー : 認証失敗
ログインエラー --> ログインフォーム表示 : エラー表示
認証済み --> データ読み込み中 : --
データ読み込み中 --> メイン画面 : データ取得成功
データ読み込み中 --> エラー画面 : データ取得失敗
メイン画面 --> 編集モード : 編集開始
編集モード --> 保存中 : 保存実行
保存中 --> メイン画面 : 保存成功
保存中 --> 編集エラー : 保存失敗
編集エラー --> 編集モード : エラー表示
メイン画面 --> セッション期限切れ : トークン期限切れ
編集モード --> セッション期限切れ : トークン期限切れ
セッション期限切れ --> 未認証 : --
エラー画面 --> データ読み込み中 : 再試行
メイン画面 --> [*] : ログアウト
実際のアプリケーション設計例
ユーザー認証システム
mermaidstateDiagram-v2
[*] --> ゲスト
ゲスト --> 登録中 : 新規登録
ゲスト --> ログイン中 : ログイン
登録中 --> メール認証待ち : 登録完了
登録中 --> 登録エラー : バリデーションエラー
登録エラー --> ゲスト : 修正
メール認証待ち --> アクティブユーザー : メール認証完了
メール認証待ち --> 認証期限切れ : 期限切れ
認証期限切れ --> ゲスト : 再登録要求
ログイン中 --> アクティブユーザー : ログイン成功
ログイン中 --> ログインエラー : ログイン失敗
ログインエラー --> ゲスト : 再試行
ログインエラー --> アカウントロック : 試行回数上限
アカウントロック --> ゲスト : ロック解除
アクティブユーザー --> パスワード変更中 : パスワード変更
パスワード変更中 --> アクティブユーザー : 変更完了
パスワード変更中 --> アクティブユーザー : 変更キャンセル
アクティブユーザー --> 一時停止 : 管理者による停止
一時停止 --> アクティブユーザー : 停止解除
一時停止 --> 削除済み : アカウント削除
アクティブユーザー --> [*] : ログアウト
削除済み --> [*]
注文処理システム
mermaidstateDiagram-v2
[*] --> カート空
カート空 --> 商品選択中 : 商品追加
商品選択中 --> カート内商品あり : 商品確定
商品選択中 --> カート空 : キャンセル
カート内商品あり --> 配送情報入力中 : 注文手続き開始
カート内商品あり --> 商品選択中 : 商品変更
カート内商品あり --> カート空 : カート空にする
配送情報入力中 --> 決済方法選択中 : 配送情報確定
配送情報入力中 --> カート内商品あり : 戻る
決済方法選択中 --> 注文確認中 : 決済方法確定
決済方法選択中 --> 配送情報入力中 : 戻る
注文確認中 --> 決済処理中 : 注文確定
注文確認中 --> 決済方法選択中 : 戻る
決済処理中 --> 注文完了 : 決済成功
決済処理中 --> 決済エラー : 決済失敗
決済エラー --> 注文確認中 : 再試行
決済エラー --> カート内商品あり : 注文中止
注文完了 --> 出荷準備中 : --
出荷準備中 --> 出荷済み : 出荷完了
出荷準備中 --> 注文キャンセル済み : キャンセル要求
出荷済み --> 配送中 : 配送開始
配送中 --> 配送完了 : 配送完了
配送完了 --> [*]
注文キャンセル済み --> [*]
note for 決済処理中 : タイムアウト: 30秒
note for 出荷準備中 : 在庫確認・引当処理
ER ダイアグラム(ER Diagram)でデータベース設計
ER ダイアグラムは、データベースの構造とエンティティ間の関係を表現する重要なツールです。Mermaid では、データモデリングから実際のテーブル設計まで、視覚的に理解しやすい図を作成できます。
エンティティとリレーションシップの定義
基本的な ER ダイアグラム
mermaiderDiagram
USER {
int user_id PK
string username UK
string email UK
string password
datetime created_at
datetime updated_at
}
PROFILE {
int profile_id PK
int user_id FK
string first_name
string last_name
date birth_date
string phone
text bio
}
POST {
int post_id PK
int user_id FK
string title
text content
datetime published_at
datetime created_at
datetime updated_at
}
USER ||--|| PROFILE : has
USER ||--o{ POST : creates
詳細なエンティティ定義
mermaiderDiagram
CUSTOMER {
uuid customer_id PK "顧客ID"
string email UK "メールアドレス"
string first_name "名"
string last_name "姓"
string phone "電話番号"
date birth_date "生年月日"
enum gender "性別"
datetime created_at "作成日時"
datetime updated_at "更新日時"
boolean is_active "アクティブフラグ"
}
ADDRESS {
uuid address_id PK "住所ID"
uuid customer_id FK "顧客ID"
string type "住所タイプ"
string postal_code "郵便番号"
string prefecture "都道府県"
string city "市区町村"
string street "番地"
string building "建物名"
boolean is_default "デフォルトフラグ"
}
CUSTOMER ||--o{ ADDRESS : "住所を持つ"
カーディナリティと制約の表現
関係の種類と記法
mermaiderDiagram
%% 1対1の関係
USER ||--|| USER_PROFILE : has
%% 1対多の関係
CATEGORY ||--o{ PRODUCT : contains
%% 多対多の関係
PRODUCT }o--o{ TAG : "tagged with"
%% オプショナルな関係
ORDER ||--o| COUPON : uses
USER {
int id PK
string username UK
string email UK
}
USER_PROFILE {
int id PK
int user_id FK
string bio
string avatar_url
}
CATEGORY {
int id PK
string name UK
string description
}
PRODUCT {
int id PK
int category_id FK
string name
decimal price
int stock
}
TAG {
int id PK
string name UK
string color
}
ORDER {
int id PK
int user_id FK
datetime order_date
decimal total_amount
}
COUPON {
int id PK
string code UK
decimal discount_rate
date valid_until
}
実際のデータベーススキーマ設計
EC サイトのデータベース設計
mermaiderDiagram
CUSTOMER {
uuid customer_id PK
string email UK
string password_hash
string first_name
string last_name
string phone
date birth_date
enum gender
datetime registered_at
datetime last_login_at
boolean is_verified
boolean is_active
}
CUSTOMER_ADDRESS {
uuid address_id PK
uuid customer_id FK
enum address_type
string postal_code
string prefecture
string city
string street_address
string building_name
boolean is_default
datetime created_at
}
CATEGORY {
int category_id PK
int parent_category_id FK
string category_name UK
string description
string image_url
int sort_order
boolean is_active
}
PRODUCT {
uuid product_id PK
int category_id FK
string product_name
text description
decimal price
decimal cost_price
int stock_quantity
int reserved_quantity
string sku UK
json specifications
datetime created_at
datetime updated_at
boolean is_active
}
PRODUCT_IMAGE {
uuid image_id PK
uuid product_id FK
string image_url
string alt_text
int sort_order
boolean is_primary
}
CART {
uuid cart_id PK
uuid customer_id FK
datetime created_at
datetime updated_at
}
CART_ITEM {
uuid cart_item_id PK
uuid cart_id FK
uuid product_id FK
int quantity
decimal unit_price
datetime added_at
}
ORDER {
uuid order_id PK
uuid customer_id FK
string order_number UK
datetime order_date
enum order_status
decimal subtotal
decimal tax_amount
decimal shipping_fee
decimal discount_amount
decimal total_amount
json shipping_address
json billing_address
datetime created_at
datetime updated_at
}
ORDER_ITEM {
uuid order_item_id PK
uuid order_id FK
uuid product_id FK
string product_name
int quantity
decimal unit_price
decimal total_price
}
PAYMENT {
uuid payment_id PK
uuid order_id FK
enum payment_method
enum payment_status
decimal amount
string transaction_id
datetime processed_at
text payment_details
}
REVIEW {
uuid review_id PK
uuid product_id FK
uuid customer_id FK
int rating
string title
text comment
datetime created_at
boolean is_verified_purchase
}
%% 関係の定義
CUSTOMER ||--o{ CUSTOMER_ADDRESS : "has addresses"
CUSTOMER ||--|| CART : "has cart"
CUSTOMER ||--o{ ORDER : "places orders"
CUSTOMER ||--o{ REVIEW : "writes reviews"
CATEGORY ||--o{ CATEGORY : "has subcategories"
CATEGORY ||--o{ PRODUCT : "contains products"
PRODUCT ||--o{ PRODUCT_IMAGE : "has images"
PRODUCT ||--o{ CART_ITEM : "added to cart"
PRODUCT ||--o{ ORDER_ITEM : "ordered"
PRODUCT ||--o{ REVIEW : "receives reviews"
CART ||--o{ CART_ITEM : "contains items"
ORDER ||--o{ ORDER_ITEM : "contains items"
ORDER ||--|| PAYMENT : "has payment"
正規化とテーブル関係の可視化
正規化プロセスの表現
mermaiderDiagram
%% 第1正規形違反の例(繰り返しグループあり)
STUDENT_UNNORMALIZED {
int student_id PK
string student_name
string course1
string course2
string course3
string instructor1
string instructor2
string instructor3
}
%% 第1正規形適用後
STUDENT {
int student_id PK
string student_name
}
ENROLLMENT {
int enrollment_id PK
int student_id FK
string course_name
string instructor_name
}
%% 第2正規形適用後(部分関数従属を排除)
COURSE {
string course_code PK
string course_name UK
string instructor_name
int credits
}
STUDENT_COURSE {
int enrollment_id PK
int student_id FK
string course_code FK
date enrollment_date
char grade
}
%% 第3正規形適用後(推移関数従属を排除)
INSTRUCTOR {
int instructor_id PK
string instructor_name UK
string department
string email
}
COURSE_NORMALIZED {
string course_code PK
string course_name UK
int instructor_id FK
int credits
string description
}
%% 関係の定義
STUDENT ||--o{ STUDENT_COURSE : enrolls
COURSE_NORMALIZED ||--o{ STUDENT_COURSE : "enrolled by"
INSTRUCTOR ||--o{ COURSE_NORMALIZED : teaches
まとめ
この記事では、Mermaid を活用した システム設計品質向上のための 3 つの重要なダイアグラム について詳しく解説いたしました。
クラス図の価値 オブジェクト指向設計における クラス間の関係性を明確にし、保守性の高いアーキテクチャ設計を実現できます。特に、継承やインターフェース実装、デザインパターンの表現により、チーム全体での設計理解を深められます。
状態図の効果 システムやアプリケーションの状態遷移を可視化することで、UI/UX フローの最適化や、複雑なビジネスロジックの明確化が可能になります。並行状態や複合状態の表現により、現実的なシステム動作を正確にモデリングできます。
ER ダイアグラムの重要性 データベース設計の品質向上と、正規化プロセスの可視化により、効率的で整合性の取れたデータ構造を構築できます。特に、大規模システムでのデータ関係の把握と保守性確保に威力を発揮します。
次回の最終記事では、実践例とカスタマイズテクニック を通じて、これまで学習した内容の総仕上げと、業務での効果的な活用方法をご紹介いたします。
関連リンク
- review
もう三日坊主とはサヨナラ!『続ける思考』井上新八
- review
チーム開発が劇的に変わった!『リーダブルコード』Dustin Boswell & Trevor Foucher
- review
アジャイル初心者でも大丈夫!『アジャイルサムライ − 達人開発者への道』Jonathan Rasmusson
- review
人生が作品になる!『自分の中に毒を持て』岡本太郎
- review
体調不良の 99%が解決!『眠れなくなるほど面白い 図解 自律神経の話』小林弘幸著で学ぶ、現代人必須の自律神経コントロール術と人生を変える健康革命
- review
衝撃の事実!『睡眠こそ最強の解決策である』マシュー・ウォーカー著が明かす、99%の人が知らない睡眠の驚くべき真実と人生を変える科学的メカニズム