面向接口编程
???? 面向接口编程的核心是利用接口回调,用接口变量去访问自己被实现了的方法,这样做也满足开闭原则,即对修改关闭,对扩展开放。
一、面向接口编程UML图示
二、面向接口编程代码
public class interfaceOrientedProgram {
public static void main(String[] args) {
Simulor simulor = new Simulor();
simulor.playsound(new Dog());
simulor.playsound(new Cat());
System.out.println(simulor.gerAnimalName(new Dog()));
System.out.println(simulor.gerAnimalName(new Cat()));
}
}
interface Animal{
void cry();
String getAnimalName();
}
class Dog implements Animal{
@Override
public void cry() {
System.out.println("汪汪");
}
public String getAnimalName(){
return "小白狗";
}
}
class Cat implements Animal{
@Override
public void cry() {
System.out.println("喵喵");
}
public String getAnimalName(){
return "小花猫";
}
}
class Simulor{
public void playsound(Animal animal){
animal.cry();
}
public String gerAnimalName(Animal animal){
return animal.getAnimalName();
}
}
|