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' );
陈大卫

界面更加灵活。这样,并不是所有苍蝇都被强制从同一个基类继承(php不支持多重继承)

所以

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

有时并不需要灵活性。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章