douhuang75397 2015-01-07 19:48 采纳率: 0%
浏览 66
已采纳

PHP使用抽象类或接口?

In this piece of code is it better to use abstract classes in place of the interfaces or is it good as it currently is? If so, why?

/** 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条回答 默认 最新

  • douyouming9180 2015-01-07 19:54
    关注

    the interface is more flexible. this way not everything that flies is forced to inherit from the same base class (php doesnt support multiple inheritance)

    so

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

    sometimes flexibility is not desired.

    abstract classes can also provide function definitions which will reduce code duplication if multiple flying classes required the same fly() method

    hope that helps you understand your choice

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法