文章摘要
这篇文章介绍了PHP中的接口实现、具体实现类、抽象类以及扩展抽象类的相关概念。文章通过示例展示了如何通过继承和方法重写在扩展抽象类(`RefinedAbstraction`)中实现功能。具体实现类(如`ConcreteImplementorA`和`ConcreteImplementorB`)继承了接口,并实现了`operationImpl`方法。文章还展示了如何通过动态创建实例并调用方法,最终输出了预期的结果。文章重点突出了面向对象编程中的方法传递和层次化架构。
<?php
// 实现类接口
interface Implementor
{
public function operationImpl();
}
// 具体实现类A
class ConcreteImplementorA implements Implementor
{
public function operationImpl()
{
return “ConcreteImplementorA operation.”;
}
}
// 具体实现类B
class ConcreteImplementorB implements Implementor
{
public function operationImpl()
{
return “ConcreteImplementorB operation.”;
}
}
// 抽象类
abstract class Abstraction
{
protected $implementor;
public function __construct(Implementor $implementor)
{
$this->implementor=$implementor;
}
abstract public function operation();
}
// 扩展抽象类
class RefinedAbstraction extends Abstraction
{
public function operation()
{
return $this->implementor->operationImpl();
}
}
// 客户端代码
$implementorA=new ConcreteImplementorA();
$abstraction=new RefinedAbstraction($implementorA);
echo $abstraction->operation(); // 输出 “ConcreteImplementorA operation.”
// 实现类接口
interface Implementor
{
public function operationImpl();
}
// 具体实现类A
class ConcreteImplementorA implements Implementor
{
public function operationImpl()
{
return “ConcreteImplementorA operation.”;
}
}
// 具体实现类B
class ConcreteImplementorB implements Implementor
{
public function operationImpl()
{
return “ConcreteImplementorB operation.”;
}
}
// 抽象类
abstract class Abstraction
{
protected $implementor;
public function __construct(Implementor $implementor)
{
$this->implementor=$implementor;
}
abstract public function operation();
}
// 扩展抽象类
class RefinedAbstraction extends Abstraction
{
public function operation()
{
return $this->implementor->operationImpl();
}
}
// 客户端代码
$implementorA=new ConcreteImplementorA();
$abstraction=new RefinedAbstraction($implementorA);
echo $abstraction->operation(); // 输出 “ConcreteImplementorA operation.”
© 版权声明
文章版权归作者所有,未经允许请勿转载。