※開放封閉原則:
新增開放,修改封閉public class People { public String function1(){ return "功能1"; } public String function2(){ return "功能2"; } } People p = new People(); System.out.println(p.function1()); System.out.println(p.function2());
※假設要新增功能3,就要修改了,這時就違返了開放封閉原則
※
public interface People { public String function(); } public class Funtion1 implements People { @Override public String function() { return "功能1"; } } public class Funtion2 implements People { @Override public String function() { return "功能2"; } } People e1 = new Funtion1(); System.out.println(e1.function()); People e2 = new Funtion2(); System.out.println(e2.function());
※將 People 改成介面或抽象,以後都不會對 People 做修改
此時新功能只要新增子類,然後繼承 People
※
@FunctionalInterface public interface People { public String function(); } People e1 = () -> "功能1"; System.out.println(e1.function()); People e2 = () -> "功能2"; System.out.println(e2.function());
※如果父類 People 剛好只有一個功能要實作,還可以用 Java8,這時連子類都可以省略了
沒有留言:
張貼留言