PHP使用抽象类或接口?

时间:2015-01-07 19:48:32

标签: php interface abstract-class factory-pattern abstraction

在这段代码中,最好使用抽象类来代替接口,还是现在好呢?如果是这样,为什么?

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

1 个答案:

答案 0 :(得分:4)

界面更灵活。这种方式并不是所有苍蝇都被迫从同一个基类继承(php不支持多重继承)

所以

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

有时候不需要灵活性。

抽象类还可以提供函数定义,如果多个飞行类需要相同的fly()方法,这将减少代码重复

希望能帮助您理解您的选择