Home > Backend Development > PHP Tutorial > php设计模式的六大原则(五):依赖倒置原则

php设计模式的六大原则(五):依赖倒置原则

WBOY
Release: 2016-06-23 13:23:23
Original
1133 people have browsed it

依赖倒置原则(DSP)

<?php// 司机开奔驰,未用依赖倒置原则的写法class Benz{	public function run(){			return " Benz is runing!!!";	}}class Driver{	public function drive(Benz $car){			echo $car -> run();	}}class Client{		public static function doing(){			$driver = new Driver();		$driver -> drive( new Benz() );	}}Client :: doing();// 那么如果司机想开宝马呢?,是不是就要修改Driver了,这就违反了开闭原则了,怎么能只在Client添加代码就让宝马车也会开呢?interface ICar{		//定义一个汽车接口	public function run();}class BMW implements ICar{	public function run(){			return "BMW is runing !!!";	}}class Benz implements ICar{	public function run(){			return "Benz is runing !!!";	}}interface IDriver{		//定义一个司机接口,以防以后有A照,B照,C照的	public function drive(ICar $car);}class Driver implements IDriver{	public function drive(ICar $car){			echo "<br>" . $car -> run();	}}class Client{	public static function doing(){			$driver = new Driver();		$driver -> drive( new BMW() ); //开宝马		$driver -> drive( new Benz() ); //开奔驰	        .	        .	        .	        .	}}Client :: doing();?>
Copy after login

这么简单,学会了吧?依赖倒置原则核心一句话:面向接口编程。



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template