开闭原则:对修改是封闭的,对扩展是开放的,不要违反开闭原则。
可以使用多态解决这个问题。父类的引用变量可以引用子类是对象。
写的越是抽象,越是稳定
public class printerDemo { public static void main(String[] args) { /*colorPrinter cp = new colorPrinter("惠普"); blackPrinter bp = new blackPrinter("联想");*/ printer p1 = new colorPrinter("惠普"); printer p2 = new blackPrinter("联想"); printer p3 = new DDDPrinter("索尼"); school sch = new school(); /*sch.setBlackPrinter(bp); sch.setColorPrinter(cp);*/ sch.setPriner(p1); sch.setPriner(p2); /*cp.print("abc"); bp.print("abc");*/ p1.print("hello"); p2.print("hello"); p3.print("hello"); } } class school{ /*private colorPrinter cp = null; private blackPrinter bp = null;*/ private printer p = null; /*public void setColorPrinter(colorPrinter cp) { this.cp = cp; } public void setBlackPrinter(blackPrinter bp) { this.bp = bp; }*/ public void setPriner(printer p) { this.p = p; } public void print(String content) { /*cp.print(content); bp.print(content);*/ p.print(content); } } class printer{ private String brand; public String getBrand() { return brand; } public printer(String brand) { this.brand = brand; } public 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 DDDPrinter extends printer{ public DDDPrinter(String brand) { super(brand); } public void print(String content) { System.out.println(getBrand()+"3D打印:"+content); } }