2017-02-11 9 views
1

私は非常に困難な時間を、典型的には3〜5個の小さなモジュールまたはクラスで構成されていると書いています。この問題は、これらのサブコンポーネントを拡張する必要がある場合に発生しますが、メインモジュールはすでにベースバージョンを作成して実装しています。複数コンポーネントクラス用のOOP

// main module design 

class Car { 
    constructor() { 
    this.horn = new Horn(); 
    this.horn.on('honk', function() { 
     console.log('honked'); 
    }) 
    } 
} 

class Horn { 
    constructor() { 
    this.sound = 'hornA.wav' 
    } 
} 

// extended module design 

class RaceCar extends Car { 
    constructor() { 
    super(); 
    this.horn = new RaceHorn(); 

    // event handler is now missing 
    } 
} 

class RaceHorn extends Horn { 
    constructor() { 
    super(); 
    this.horn = 'hornB.wav' 
    } 
} 

私の本当の問題は、より多くのコンポーネントと多くのセットアップ要件とモジュールを必要とする一方で、これは確かに非常に単純化された例です。 initまたはsetupまたはそれに類する機能に別のものを入れることができると私は理解していますが、私にとっては本質的に間違っているようです。

+1

継承を構成する手段として使用しないでください。 RaceCarは本当にちょうど別のホーンで設定されたCarインスタンスでなければなりません。すべてが工場で行われています。 – plalx

+0

あなたはおそらく異なったホーンを必要としないでしょう、ちょうど再生するサウンドファイル名のパラメータを与えてください。 – Bergi

答えて

1

この問題に関係するものについては、パラメータを介して値を渡すことを強くお勧めします。デフォルトのパラメータは、これは非常に厄介取得することができ、その代わりに、あなたはこれらのは、あなたが使用できる2つのモジュール式のパターンであり、かつ構造の種類に応じて初期化メソッド

// main module design 

class Car { 
    constructor() { ... } 
    init(hornType=Horn){ 
    this.initHorn(hornType); 
    } 
    initHorn(hornType=Horn){ 
    this.horn = new Horn(); 
    this.horn.on('honk', function() { 
     console.log('honked'); 
    }) 
    } 
} 

class Horn { 
    constructor() { 
    this.sound = 'hornA.wav' 
    } 
} 

// extended module design 

class RaceCar extends Car { 
    constructor() { 
    super(); 
    } 
    init(hornType=RaceHorn){ 
    this.initHorn(hornType); 
    } 
} 

class RaceHorn extends Horn { 
    constructor() { 
    super(); 
    this.sound = 'hornB.wav' 
    } 
} 

const raceCar = new RaceCar(); 
raceCar.init(); 

を使用することができます

// main module design 

class Car { 
    constructor(parametrizedHorn=Horn) { 
    this.horn = new parametrizedHorn(); 
    this.horn.on('honk', function() { 
     console.log('honked'); 
    }) 
    } 
} 

class Horn { 
    constructor() { 
    this.sound = 'hornA.wav' 
    } 
} 

// extended module design 

class RaceCar extends Car { 
    constructor() { 
    super(RaceHorn); 
    } 
} 

class RaceHorn extends Horn { 
    constructor() { 
    super(); 
    this.sound = 'hornB.wav' 
    } 
} 

多くを助けることができますすでに使用している場合は、どちらが最善であるかを判断できます。最後に、クラスの内容をパラメータ化するか、メソッドをさらにモジュール化します。

関連する問題