概念
高层模块不该依赖底层模块,二者都该依赖其抽象(接口、抽象类);抽象不该依赖其细节;细节依赖抽象;
代码实现
<?phpinterface Str{public function randStr();}class Letter implements Str{public function randStr(){$arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];$indexs = array_rand($arr, 4);$str = '';foreach ($indexs as $index) {$str .= $arr[$index];}return $str;}}class Num implements Str{public function randStr(){return mt_rand(1000, 9999);}}class C{public function boot(Str $str){echo "生成字符串预计需要3秒..." . PHP_EOL;for ($i = 3; $i > 0; $i--) {sleep(1);echo "{$i}秒" . PHP_EOL;}echo $str->randStr() . PHP_EOL;}}$letter = new Letter();$num = new Num();$c = new C();$c->boot($letter);$c->boot($num);
