文章摘要
这篇文章介绍了Java中的接口和实现类的概念。首先定义了接口`Implementor`,并提供了两个具体实现类`ConcreteImplementorA`和`ConcreteImplementorB`,它们都实现了`Implementor`接口中的`operationImpl`方法。接着,展示了如何通过抽象类`Abstraction`绑定实现类实例,并通过继承进一步扩展了这一结构。最后,文章给出了一个客户端示例,展示了如何通过实例化抽象类并调用其`operation`方法,实现了特定的行为。文章重点突出了接口继承和方法重写的机制。
<?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.”
© 版权声明
文章版权归作者所有,未经允许请勿转载。



