1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

依存関係逆転の原則(Dependency Inversion Principle、DIP)は、ソフトウェア設計の原則の一つ。高レベルモジュールが低レベルモジュールに直接依存しないように設計することを意味する。代わりに、両方が抽象化に依存する。これにより、モジュール間の結合が緩やかになり、保守性や拡張性が向上する。

依存関係逆転の原則を使用していない
class EmailService
  def send_email(user_email)
    # 電子メール送信の実装
  end
end

class UserAuthentication
  def initialize(user_email)
    @user_email = user_email
    @email_service = EmailService.new
  end

  def authenticate
    # 認証ロジック
    email_service.send_email(@user_email)
  end
end
依存関係逆転の原則を使用
# インターフェース
module EmailNotifier
  def send_email(user_email)
    raise NotImplementedError, "send_email must be implemented"
  end
end

# 具体的な実装
class EmailService
  include EmailNotifier

  def send_email(user_email)
    # 電子メール送信の実装
  end
end

class UserAuthentication
  def initialize(user_email, email_service)
    @user_email = user_email
    @email_service = email_service
  end

  def authenticate
    # 認証ロジック
    email_service.send_email(@user_email)
  end
end

# 使い方
email_service = EmailService.new
authenticator = UserAuthentication.new("user@example.com", email_service)
authenticator.authenticate
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?