簡體   English   中英

PHP使用抽象類還是接口?

[英]PHP use abstract class or interface?

在這段代碼中,最好是使用抽象類代替接口,還是現在好呢? 如果是這樣,為什么?

/** 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' );

界面更加靈活。 這樣,並不是所有蒼蠅都被強制從同一個基類繼承(php不支持多重繼承)

所以

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

有時並不需要靈活性。

抽象類還可以提供函數定義,如果多個飛行類需要相同的fly()方法,則可以減少代碼重復

希望能幫助您了解您的選擇

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM