開閉原則:對修改是封閉的,對擴充套件是開放的,不要違反開閉原則。
可以使用多型解決這個問題。父類的引用變數可以引用子類是物件。
寫的越是抽象,越是穩定
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); } }