jpskill.com
🛠️ 開発・MCP コミュニティ

code-patterns

Common code patterns and best practices reference for quick lookup

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o code-patterns.zip https://jpskill.com/download/17511.zip && unzip -o code-patterns.zip && rm code-patterns.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17511.zip -OutFile "$d\code-patterns.zip"; Expand-Archive "$d\code-patterns.zip" -DestinationPath $d -Force; ri "$d\code-patterns.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して code-patterns.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → code-patterns フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

コードパターンリファレンス

一般的なパターンに関するクイックリファレンスです。これらは厳格なテンプレートとしてではなく、出発点として使用してください。

生成に関するパターン

Factory

// When: 正確なクラスを指定せずにオブジェクトを作成する場合
interface Product { use(): void }

class ConcreteProductA implements Product {
  use() { console.log('Using A') }
}

class ProductFactory {
  static create(type: string): Product {
    const products = { a: ConcreteProductA };
    return new products[type]();
  }
}

Builder

// When: 多くのオプションパラメータを持つ複雑なオブジェクトの構築
class QueryBuilder {
  private query = { select: '*', from: '', where: [] };

  select(fields: string) { this.query.select = fields; return this; }
  from(table: string) { this.query.from = table; return this; }
  where(condition: string) { this.query.where.push(condition); return this; }
  build() { return this.query; }
}

// Usage
const query = new QueryBuilder()
  .select('name, email')
  .from('users')
  .where('active = true')
  .build();

Singleton

// When: 厳密に1つのインスタンスが必要な場合(控えめに使用してください!)
class Database {
  private static instance: Database;
  private constructor() {}

  static getInstance(): Database {
    if (!Database.instance) {
      Database.instance = new Database();
    }
    return Database.instance;
  }
}

構造に関するパターン

Adapter

// When: 互換性のないインターフェースを連携させる場合
interface ModernLogger { log(msg: string): void }

class LegacyLogger {
  writeLog(message: string, level: number) { /* ... */ }
}

class LoggerAdapter implements ModernLogger {
  constructor(private legacy: LegacyLogger) {}
  log(msg: string) { this.legacy.writeLog(msg, 1); }
}

Decorator

// When: 元のオブジェクトを変更せずに動作を追加する場合
interface Coffee { cost(): number; description(): string }

class SimpleCoffee implements Coffee {
  cost() { return 5; }
  description() { return 'Coffee'; }
}

class MilkDecorator implements Coffee {
  constructor(private coffee: Coffee) {}
  cost() { return this.coffee.cost() + 2; }
  description() { return this.coffee.description() + ' + Milk'; }
}

振る舞いに関するパターン

Strategy

// When: アルゴリズムを実行時に選択可能にする場合
interface PaymentStrategy {
  pay(amount: number): void;
}

class CreditCardPayment implements PaymentStrategy {
  pay(amount: number) { console.log(`Paid ${amount} via credit card`); }
}

class PayPalPayment implements PaymentStrategy {
  pay(amount: number) { console.log(`Paid ${amount} via PayPal`); }
}

class Checkout {
  constructor(private strategy: PaymentStrategy) {}
  process(amount: number) { this.strategy.pay(amount); }
}

Observer

// When: オブジェクトの状態変化を通知する必要がある場合
type Listener<T> = (data: T) => void;

class EventEmitter<T> {
  private listeners: Listener<T>[] = [];

  subscribe(listener: Listener<T>) {
    this.listeners.push(listener);
    return () => this.listeners = this.listeners.filter(l => l !== listener);
  }

  emit(data: T) {
    this.listeners.forEach(l => l(data));
  }
}

エラー処理に関するパターン

Result Type

// When: エラーが例外ではなく、予期される場合
type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function divide(a: number, b: number): Result<number, string> {
  if (b === 0) return { ok: false, error: 'Division by zero' };
  return { ok: true, value: a / b };
}

const result = divide(10, 2);
if (result.ok) {
  console.log(result.value); // 5
} else {
  console.error(result.error);
}

Retry with Backoff

// When: 一時的なエラーが予想される場合
async function retry<T>(
  fn: () => Promise<T>,
  attempts = 3,
  delay = 1000
): Promise<T> {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (e) {
      if (i === attempts - 1) throw e;
      await new Promise(r => setTimeout(r, delay * Math.pow(2, i)));
    }
  }
  throw new Error('Unreachable');
}

非同期処理に関するパターン

Promise Queue

// When: 並行する非同期操作を制限する場合
class PromiseQueue {
  private queue: (() => Promise<any>)[] = [];
  private running = 0;

  constructor(private concurrency: number) {}

  add<T>(fn: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push(async () => {
        try { resolve(await fn()); }
        catch (e) { reject(e); }
      });
      this.process();
    });
  }

  private async process() {
    if (this.running >= this.concurrency || !this.queue.length) return;
    this.running++;
    await this.queue.shift()!();
    this.running--;
    this.process();
  }
}

Debounce

// When: 短時間に連続する関数呼び出しを制限する場合
function debounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}

データに関するパターン

Repository

// When: データアクセスを抽象化する場合
interface Repository<T> {
  findById(id: string): Promise<T | null>;
  findAll(): Promise<T[]>;
  save(entity: T): Promise<T>;
  delete(id: string): Promise<void>;
}

class UserRepository implements Repository<User> {
  constructor(private db: Database) {}

  async findById(id: string) {
    return this.db.query('SELECT * FROM users WHERE id = ?', [id]);
  }
  // ... 他のメソッド
}

Unit of Work

// When: 複数のリポジトリにわたる書き込みを調整する場合
class UnitOfWork {
  private operations: (() => Promise<void>)[] = [];

  register(operation: () => Promise<void>) {
    this.operations.push(operation);
  }

  async commit() {
    await this.db.beginTransaction();
    try {
      for (const op of this.operations) await op();
      await this.db.commit();
    } catch (e) {
      await this.db.rollback();
      throw e;
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Code Patterns Reference

Quick reference for common patterns. Use these as starting points, not rigid templates.

Creational Patterns

Factory

// When: Creating objects without specifying exact class
interface Product { use(): void }

class ConcreteProductA implements Product {
  use() { console.log('Using A') }
}

class ProductFactory {
  static create(type: string): Product {
    const products = { a: ConcreteProductA };
    return new products[type]();
  }
}

Builder

// When: Complex object construction with many optional params
class QueryBuilder {
  private query = { select: '*', from: '', where: [] };

  select(fields: string) { this.query.select = fields; return this; }
  from(table: string) { this.query.from = table; return this; }
  where(condition: string) { this.query.where.push(condition); return this; }
  build() { return this.query; }
}

// Usage
const query = new QueryBuilder()
  .select('name, email')
  .from('users')
  .where('active = true')
  .build();

Singleton

// When: Exactly one instance needed (use sparingly!)
class Database {
  private static instance: Database;
  private constructor() {}

  static getInstance(): Database {
    if (!Database.instance) {
      Database.instance = new Database();
    }
    return Database.instance;
  }
}

Structural Patterns

Adapter

// When: Making incompatible interfaces work together
interface ModernLogger { log(msg: string): void }

class LegacyLogger {
  writeLog(message: string, level: number) { /* ... */ }
}

class LoggerAdapter implements ModernLogger {
  constructor(private legacy: LegacyLogger) {}
  log(msg: string) { this.legacy.writeLog(msg, 1); }
}

Decorator

// When: Adding behavior without modifying original
interface Coffee { cost(): number; description(): string }

class SimpleCoffee implements Coffee {
  cost() { return 5; }
  description() { return 'Coffee'; }
}

class MilkDecorator implements Coffee {
  constructor(private coffee: Coffee) {}
  cost() { return this.coffee.cost() + 2; }
  description() { return this.coffee.description() + ' + Milk'; }
}

Behavioral Patterns

Strategy

// When: Algorithm should be selectable at runtime
interface PaymentStrategy {
  pay(amount: number): void;
}

class CreditCardPayment implements PaymentStrategy {
  pay(amount: number) { console.log(`Paid ${amount} via credit card`); }
}

class PayPalPayment implements PaymentStrategy {
  pay(amount: number) { console.log(`Paid ${amount} via PayPal`); }
}

class Checkout {
  constructor(private strategy: PaymentStrategy) {}
  process(amount: number) { this.strategy.pay(amount); }
}

Observer

// When: Objects need to be notified of state changes
type Listener<T> = (data: T) => void;

class EventEmitter<T> {
  private listeners: Listener<T>[] = [];

  subscribe(listener: Listener<T>) {
    this.listeners.push(listener);
    return () => this.listeners = this.listeners.filter(l => l !== listener);
  }

  emit(data: T) {
    this.listeners.forEach(l => l(data));
  }
}

Error Handling Patterns

Result Type

// When: Errors are expected, not exceptional
type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function divide(a: number, b: number): Result<number, string> {
  if (b === 0) return { ok: false, error: 'Division by zero' };
  return { ok: true, value: a / b };
}

const result = divide(10, 2);
if (result.ok) {
  console.log(result.value); // 5
} else {
  console.error(result.error);
}

Retry with Backoff

// When: Transient failures are expected
async function retry<T>(
  fn: () => Promise<T>,
  attempts = 3,
  delay = 1000
): Promise<T> {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (e) {
      if (i === attempts - 1) throw e;
      await new Promise(r => setTimeout(r, delay * Math.pow(2, i)));
    }
  }
  throw new Error('Unreachable');
}

Async Patterns

Promise Queue

// When: Limiting concurrent async operations
class PromiseQueue {
  private queue: (() => Promise<any>)[] = [];
  private running = 0;

  constructor(private concurrency: number) {}

  add<T>(fn: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push(async () => {
        try { resolve(await fn()); }
        catch (e) { reject(e); }
      });
      this.process();
    });
  }

  private async process() {
    if (this.running >= this.concurrency || !this.queue.length) return;
    this.running++;
    await this.queue.shift()!();
    this.running--;
    this.process();
  }
}

Debounce

// When: Limiting rapid-fire function calls
function debounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}

Data Patterns

Repository

// When: Abstracting data access
interface Repository<T> {
  findById(id: string): Promise<T | null>;
  findAll(): Promise<T[]>;
  save(entity: T): Promise<T>;
  delete(id: string): Promise<void>;
}

class UserRepository implements Repository<User> {
  constructor(private db: Database) {}

  async findById(id: string) {
    return this.db.query('SELECT * FROM users WHERE id = ?', [id]);
  }
  // ... other methods
}

Unit of Work

// When: Coordinating writes across multiple repositories
class UnitOfWork {
  private operations: (() => Promise<void>)[] = [];

  register(operation: () => Promise<void>) {
    this.operations.push(operation);
  }

  async commit() {
    await this.db.beginTransaction();
    try {
      for (const op of this.operations) await op();
      await this.db.commit();
    } catch (e) {
      await this.db.rollback();
      throw e;
    }
  }
}

When to Use Each

Problem Pattern
Complex object creation Builder
Multiple similar objects Factory
Global state (careful!) Singleton
Incompatible interfaces Adapter
Adding features dynamically Decorator
Swappable algorithms Strategy
Event-based communication Observer
Expected failures Result Type
Transient failures Retry
Rate limiting Debounce/Throttle
Data access abstraction Repository
Transactional consistency Unit of Work