我有个想法,一个类的行为是根据这个类的环境决定的。比如程序员在办公室可以写代码,在家还必须带孩子。
用Groovy来实现
1. Programer.groovy
package art.groovy
class Programer {
String name;
}
2. ProgramerHomeMixin.groovy
package art.groovy
class ProgramerHomeMixin {
def takeCareOfBaby = {
println "I'm $name, I am taking care of my baby at home"
}
}
3. ProgramerOfficeMixin.groovy
package art.groovy
class ProgramerOfficeMixin {
def writeCode={
println "I am $name, I am writing code in my office, don't disturb me"
}
}
4. ProgrammerMixinTest.groovy
package art.groovy;
import groovy.util.GroovyTestCase;
class ProgrammerMixinTest extends GroovyTestCase {
private Programer programmer;
void testBehaviorDependsOnContext(){
Programer.mixin ProgramerOfficeMixin
programmer = new Programer(name: "alex")
programmer.writeCode()
}
void testBehaviorDependsOnContext2(){
Programer.mixin ProgramerHomeMixin
programmer = new Programer(name: "alex")
programmer.takeCareOfBaby()
}
}