- 依賴抽象類別,不要依賴具象類別。
簡單的說就是class 之間用interface/abstract 來溝通
下面是個簡單的人吃飯的例子。
class EatRiceBehavior { void eat() { System.out.println("Person_EATRice");
} } public class Person { EatRiceBehavior behavior=new EatRiceBehavior();
public void eat() { // TODO Auto-generated method stub behavior.eat(); } public static void main(String[] args) { Person person = new Person(); person.eat(); } }
但是當我想新增人吃麵的行為,原本的程式就不能使用了,因為他依賴於具象類別(EatRiceBehavior ),所以我就必須在class 裡面增加 EatNoodle Nbehavior; 類似這樣的參數,接著當我新增了越來越多的物件時這段程式就會變成類似下面這樣
public class Person { EatBehavior behavior;
EatNoodle Nbehavior;
Eatdumpling Dbehavior;
public void eat(string val) { // TODO Auto-generated method stub if(val.equals("rice")) behavior.eat();
else if(val.equals("noodle")) Nbehavior.eat();
else Dbehavior.eat(); } public static void main(String[] args) { Person person = new Person(); person.eat("rice"); } }
這樣的程式是非常可怕的,難以維護且重複性極高,
這時候還好有Dependency Inversion Principle,他告訴我們依賴於抽象而不依賴於具體類別
所以我們就可以寫出下面的例子
interface Behavior { void eat(); } class EatRiceBehavior implements Behavior { @Override public void eat() { // TODO Auto-generated method stub System.out.println("eat rice"); } } class EatNoodleBehavior implements Behavior { @Override public void eat() { // TODO Auto-generated method stub System.out.println("eat EatNoodle"); } } class EatDumplingBehavior implements Behavior { @Override public void eat() { // TODO Auto-generated method stub System.out.println("eat Dumpling"); } } public class Person { Behavior behavior; public void eat(Behavior behavior) { behavior.eat(); } public static void main(String[] args) { Person person = new Person(); person.eat(new EatRiceBehavior());
} }
現在不管新增了甚麼行為進來,都不至於造成太大的影響。
沒有留言:
張貼留言