1.开发系统时,主体架构使用接口,接口构成系统的骨架
2.这样就可以通过更换接口的实现类来更换系统的实现
public class printerDemo{ public static void main(String[] args) { ColorPrinter cp = new ColorPrinter("惠普"); BlackPrinter bp = new BlackPrinter("联想"); Teacher teacher = new Teacher("张三",26); School school = new School(); school.setPrinter(cp); school.setPrinter(bp); school.print(school); school.print(teacher); bp.print("abc"); cp.print("abc"); } } 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()); } public String detail() { return "我是学校"; } } interface IInfo{//接口,教师和学校都有的方法 String detail(); } abstract class Printer{ private String brand; public String getBrand() { return brand; } public Printer(String brand) {//构造方法 this.brand = brand; } public abstract void print(String content) ; } class ColorPrinter extends Printer{ public ColorPrinter(String brand) { super(brand); } public void print(String content) { System.out.println(getBrand()+"彩色打印:"+content); } } class BlackPrinter extends Printer{ public BlackPrinter(String brand) { super(brand); } public void print(String content) { System.out.println(getBrand()+"黑白打印:"+content); } } class Teacher implements IInfo{ private String name; private int age; public Teacher(String name,int age) { this.name = name; this.age = age; } public String detail() { return "我的名字叫"+name+",年龄是"+age; } }