2015-01-07 83 views
0

在這段代碼中,最好是使用抽象類代替接口,還是現在它好?如果是這樣,爲什麼?PHP使用抽象類或接口?

/** contract for all flyable vehicles **/ 
interface iFlyable { 
    public function fly(); 
} 

/* concrete implementations of iFlyable interface */ 
class JumboJet implements iFlyable { 
    public function fly() { 
     return "Flying 747!"; 
    } 
} 

class FighterJet implements iFlyable { 
    public function fly() { 
     return "Flying an F22!"; 
    } 
} 

class PrivateJet implements iFlyable { 
    public function fly() { 
     return "Flying a Lear Jet!"; 
    } 
} 

/** contract for conrete Factory **/ 
/** 
* "Define an interface for creating an object, but let the classes that implement the interface 
* decide which class to instantiate. The Factory method lets a class defer instantiation to 
* subclasses." 
**/ 
interface iFlyableFactory { 
    public static function create($flyableVehicle); 
} 

/** concrete factory **/ 
class JetFactory implements iFlyableFactory { 
    /* list of available products that this specific factory makes */ 
    private static $products = array('JumboJet', 'FighterJet', 'PrivateJet'); 

    public static function create($flyableVehicle) { 
     if(in_array($flyableVehicle, JetFactory::$products)) { 
      return new $flyableVehicle; 
     } else { 
      throw new Exception('Jet not found'); 
     } 
    } 
} 

$militaryJet = JetFactory::create('FighterJet'); 
$privateJet = JetFactory::create('PrivateJet'); 
$commercialJet = JetFactory::create('JumboJet'); 
+3

這可能是更適合codereview.stackexchange .com –

+1

這也很大程度上將基於意見,但我會給出一個意見(不是答案)。我認爲你的例子太簡單了,無法確定哪個更好。例如,如果所有的飛行器都有可能存在的普遍行爲,那麼在某些情況下,可能會出現更好的代碼重用(即更改高度,改變航向,起飛和着陸)與重載行爲,那麼抽象類可能是優於界面。 –

回答

4

該接口更加靈活。是擁有這種方式不是一切都被迫從同一基類繼承

所以

class bird extends animal implements flyable 
class plane extends machine implements flyable 
class cloud implements flyable 

有時靈活性是不期望的(PHP的犯規支持多重繼承)。

抽象類還可以提供的功能定義它,如果多個飛行類需要同飛()方法

希望幫助您瞭解您的選擇將減少代碼的重複

+0

具有很多意義。 Thnaks @David Chan –