This is a little bit contrived example usage of mixin. I am looking for some help for the best practice or known pattern to solve this problem.
Consider the code below. It has two mixins: Increasable and Decreasable. Both work on a volume element, except that they assume that the volume element is referred by different names. It is quite likely possible if I am to use mixins developed by two different people or two different people.
mixin Increasable {
abstract Int volume
This increaseVolume() {
volume++
return this
}
}
mixin Decreasable {
abstract Int sameVolumeByAnotherName
This decreaseVolume() {
sameVolumeByAnotherName--
return this
}
}
class AudioSystem : Increasable, Decreasable {
override Int volume := 0
override Int sameVolumeByAnotherName {
set { &volume = it }
get { return &volume }
}
}
class Main {
Void main() {
audioSystem := AudioSystem()
echo(audioSystem.increaseVolume.increaseVolume.increaseVolume.volume)
echo(audioSystem.decreaseVolume.decreaseVolume.decreaseVolume.volume)
}
}
So the way AudioSystem provides the volume for both the mixins is by creating a kind of alias for the volume called sameVolumeByAnotherName, whose getter and setter methods simply get or set the the volume field. This program outputs the expected values: 3 and 0.
Is this the right way to solve this problem? Is there any other language feature to solve this issue?
Thank you.
brianFri 29 Oct 2010
Slaving one field from another seems about the best idea I can come up with.
rosarinjroy Fri 29 Oct 2010
This is a little bit contrived example usage of mixin. I am looking for some help for the best practice or known pattern to solve this problem.
Consider the code below. It has two mixins: Increasable and Decreasable. Both work on a volume element, except that they assume that the volume element is referred by different names. It is quite likely possible if I am to use mixins developed by two different people or two different people.
So the way AudioSystem provides the volume for both the mixins is by creating a kind of alias for the volume called sameVolumeByAnotherName, whose getter and setter methods simply get or set the the volume field. This program outputs the expected values: 3 and 0.
Is this the right way to solve this problem? Is there any other language feature to solve this issue?
Thank you.
brian Fri 29 Oct 2010
Slaving one field from another seems about the best idea I can come up with.
rosarinjroy Fri 29 Oct 2010
Thank you Brian.