考虑以下类层次结构:
Abstract class Printer{
public print(){
//code to handle printing
}
}
class LaserPrinter extends Printer{
private $file;
public setFile($file){
$this->file = $file;
}
}
class InkJetPrinter extends Printer{
private $document;
public setDocument($document){
$this->document= $document;
}
}
class ClientClass{
private $filesToPrint=array();
public __construct(InkJetPrinter $inkJetPrinter, LaserPrinter $laserPrinter){ //I was hoping to apply Dependency Inversion here by defining both inputs as type Printer instead
//constructor stuff
}
public function startPrinting(){
//some logic to extract the $files and $documents from $this->filesToPrint
//...
$this->inkJetPrinter->setDocument($document);//<---Things got messy here
$this->laserPrinter->setFile($file);//<---and here too
//...
}
}
现在这个类LaserPrinter
不能被它的父类替换,Printer
因为Printer
它没有setFile
方法。
这是否意味着他的等级制度违反了 Liskov 替代原则?不允许子类有自己的公共方法吗?