创建一个family接口,家里成员有说话的权利,写一个未实现的方法say()。
public interface family {
void say();
}
创建父亲类,实现接口family,实现说话权利的方法say()。
public class father implements family {
public void say() {
System.out.println("i am father");
}
}
创建母亲类,实现接口family,实现说话权利的方法say()。
public class mother implements family {
public void say() {
System.out.println("i am mother");
}
}
创建一个说话类,saying,里面控制家庭成员的说话。
public class saying {
void say(father father){
father.say();
}
void say(mother mother){
mother.say();
}
}
测试类text
public class text {
public static void main(String[] args){
saying a = new saying();
father person1 =new father();
mother person2 = new mother();
a.say(person1);
a.say(person2);
}
}
结果为:
i am father
i am mother
这样有个麻烦,就是如果我又有一个son类实现接口family,那么son要说话,于是又要在saying中创建
void say(son son){
system.out.println(“this is son”);
}
那么家庭成员多了,就会在saying类中写多个void say方法,传送不同的类参数,
如果把saying改成
public class saying {
void say(family family){
family.say();
}
}
那么运行刚才同样的其他代码,运行结果同样。
这样就有个好处,无论家庭中添加多少成员,你都无需到saying去注册你的说话权利,就可以发言。
自然,这样的方法就使得程序的可扩展性和维护性增强了。