4
1

More than 3 years have passed since last update.

ダイヤモンド継承

Last updated at Posted at 2021-08-29

ふと、これってダイヤモンド継承の出番か?
という場面が来たので検証してみました。

ダイヤモンド継承とは?

下記図のように親クラスから2つ以上の子クラスに継承し
孫クラスに分岐させた子クラスを継承して1つのクラスにすることです。

このメリットはクラスのメソッドを分岐させることによって、
メンテナンス性を向上させることだと思います。

実際にこれを書いているときにダイヤモンド継承をやりたいと考えた理由は
ドメイン駆動設計の構築中に1クラスのメソッドが多くなりすぎて、
分岐させられないか?と考えたのがキッカケです。

Pythonで実践

まずはダイヤモンドの一番上のこの箇所から作成します。

親クラス:共通で使用したいコンストラクタとメソッド
class AnimalCommon():
    def __init__(self, name):
        self.name = name

    def show_name(self):
        print(self.name)

続いて両脇のAnimalCommonからコンストラクタとメソッドを継承させて、
別の機能を持たせます。

子クラス:分岐して機能作成
# 分岐させた1つ目のクラス
class AnimalAction(AnimalCommon):
    def __init__(self, name):
        super().__init__(name)

    def cry(self, cry):
        print(f'{self.name}{cry}鳴く')

# 分岐させた2つ目のクラス
class AnimalStatus(AnimalCommon):
    def __init__(self, name):
        super().__init__(name)

    def disease(self):
        print(f'{self.name}は病気になった')

最後に分けて機能を作成したものを一つにまとめます。

孫クラス:実際に使用するクラス
class Animal(AnimalAction, AnimalStatus):
    def __init__(self, name):
        super().__init__(name)

このクラスをインスタンス化するとちゃんと
どのクラスで定義したメソッドも使えることが確認できます。

メソッドの実行
crow = Animal('カラス')
crow.show_name() # カラス
crow.cry('カーカー') # カラスはカーカー鳴く
crow.disease() # カラスは病気になった

今回は2つに分岐させて別機能を作成しましたが、
3つ以上でも同様に動かすことは可能です。

4
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
4
1