开发系统时,主体架构使用接口,接口构成系统的骨架 。这样就可以通过更换接口的实现类来更换系统的实现。
实例:学校要安装彩色和黑白两台打印机,分别打印教员和机构的相关信息(用接口实现)
教员和机构的相关信息都需要打印,这种like-a关系,使用接口把二者共有的特性抽象出来,在这里就是把要打印的信息抽象成接口:
detail()方法是一个抽象方法,默认可以不写abstract关键字
interface IInfo{
String detail();
}
教员类初始化教员信息,再实现IInfo方法
class Teacher implements IInfo{
private String name;
private int age;
public Teacher(String name,int age){
this.name=name;
this.age=age;
}
//实现接口IInfo的具体方法
public String detail(){
return "Hello, I'm "+name+", "+age+" years old.";
}
}
学校类安装打印机,打印数据,实现IInfo方法
class School implements IInfo{
private Printer p=null;//安装打印机
//拿父类的引用变量作为参数,好处就是可以接收任何子类的对象
//越是抽象的事物越稳定
public void setPrinter(Printer p){
this.p=p;
}
//接口的引用变量可以引用它实现类的对象
//多态,程序设计的时候主体框架使用接口或抽象类,是程序又很好的扩展性
public void print(IInfo info){
p.Print(info.detail());
}
//实现接口IInfo的具体方法
public String detail(){
return "Welcome to xxx School";
}
}
各式打印机继承了打印机类,所以打印机类的打印方法由具体的子类实现,这里的Print方法应该是一个抽象方法,打印机类是一个抽象类。
abstract class Printer{
private String brand;
public Printer(String brand){
this.brand=brand;
}
public String getBrand(){
return brand;
}
public abstract print(String content);
}
打印机子类实现具体的打印方法:
//彩色打印机
class ColorPrinter extends Printer{
public ColorPrinter(String brand){
super(brand);
}
public void print(String content){
System.out.println(getBrand()+"ColorPrinter:"+content)
}
}
class BlackPrinter extends Printer{
public BlackPrinter(String brand){
super(brand);
}
public void print(String content){
System.out.println(getBrand+"BlackPrinter:"+content);
}
}
主方法new对象:打印机对象,学校对象,教员对象
public class printerDemo{
public static void main(String []args){
colorPrinter cp=new colorPrinter("HP");//define printer "HP" is colorPrinter
BWPrinter bp=new BWPrinter("Sony");//define printer "Sony" is BWPrinter
School school=new School(); //init a school
Teacher t=new Teacher("Lily",30);
//school.setColorPrinter(cp); //The school installs colorPrinter "HP"
//school.Print("Hello Java"); //The school print content with colorPrinter
//school.setBWPrinter(bp);//The school installs BWPrinter "Sony"
//school.Print("Hello Java"); //The school print content with BWPrinter
school.setPrinter(cp);//set BWPrinter
school.print(t);//print teacher info
school.setPrinter(bp);//set colorPrinter
school.print(school);//print school info
}
}
输出结果