に入れてプッシュすることができます追加しますそれに新しいシンプルな製品。あなたのaddWheelは別の方法を保証するのに十分に異なって見えます。私は実際には、addWheelがRimsを作成する場所で、おそらく最良のソリューションと思われますが、このモデルの使い方はわかりません。
class Article
constructor:() ->
@rims = []
@tyres = []
@others = []
@wheels = []
addProduct: (variable, id) ->
variable.push(product = new SimpleProduct(id))
product
addRim: (id) ->
this.addProduct(@rims, id)
addTyre: (id) ->
this.addProduct(@tyres, id)
addOther: (id) ->
this.addProduct(@others, id)
addWheel: (rimId, tyreId) ->
wheel = new Wheel(rimId, tyreId)
@wheels.push(wheel)
wheel
ホイールはリムとタイヤを持っているという事実は、あなたがリムとタイヤのためにあなたのモデルに別々のインスタンス変数を必要としないことがあり、それがこのような巣にそれらをより良いことがあります、ここで
class Article
constructor:() ->
@others = []
@wheels = []
addOther: (id) ->
@others.push(product = new SimpleProduct(id))
product
addWheel: (rimId, tyreId) ->
wheel = new Wheel(rimId, tyreId)
@wheels.push(wheel)
wheel
rims: ->
@wheels.map((wheel) -> wheel.rim)
tyres: ->
@wheels.map((wheel) -> wheel.tyre)
class Wheel
constructor: (rim, tyre) ->
@rim = new SimpleProduct(rim)
@tyre = new SimpleProduct(tyre)
次の操作を行うことができます:
a = new Article()
a.addWheel(2,3)
a.tyres() // returns [SimpleProduct(2)]
この第二の例は、あなたがaddWheel()
メトを使用して追加されたタイヤにアクセスするためにthis.tyres
を使用しようとしている場合にのみですd。私はあなたが明確なタイヤ、リム、ホイール(タイヤとリム)を使用していることを知っています。