0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

オブジェクト指向プログラミングにおいて、柔軟性、保守性の高いソフトウェアを設計するための5つの原則の頭文字をとったマクロニム(略語)です。

5つの原則
1 単一責任の原則
2 オープン/クローズドの原則
3 リスコフの置換原則
4 インターフェース分離の原則
5 依存性逆転の原則

今回は2 オープン/クローズドの原則について説明します。

2 オープン/クローズドの原則

オープン/クローズドの原則(OCP)とは既存のクラスやモジュールを変更せずに新しい機能を追加できるように設計する原則です。これにより、既存コードを安定して保ちながら新しい機能を拡張できるため、変更に強い、柔軟なシステムを構築することができます。

例(OCP)

class MailService
{
    public function sendMail($to, $subject, $message)
    {
        // メールを送信する処理
    }
}
// メール送信機能を提供するクラス
class MailService
{
    public function sendMail($to, $subject, $message)
    {
        // メールを送信する処理
    }
}

// SMS送信機能を提供するクラス
class SMSService
{
    public function sendSMS($to, $message)
    {
        // SMSを送信する処理
    }
}
interface MessageServiceInterface
{
    public function send($to, $message);
}

class MailService implements MessageServiceInterface
{
    public function send($to, $message)
    {
        // メールを送信する処理
    }
}

class SMSService implements MessageServiceInterface
{
    public function send($to, $message)
    {
        // SMSを送信する処理
    }
}

このようにしてOCPを尊守することによって、既存のコードを安定させつつ、柔軟に新しい機能を追加、拡張させることができます。

オープン/クローズドの原則については以上です。
ありがとうございました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?