码迷,mamicode.com
首页 > 其他好文 > 详细

依赖倒置原则

时间:2015-09-24 19:10:35      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

1、依赖倒置的本质就是通过抽象(接口或者抽象类)使各个类或模块实现彼此独立。

public interface ICar{
		public void run();
	}
	
	public interface IDriver{
		public void drive(ICar car);
	}
	
	public class Driver implements IDriver{

		@Override
		public void drive(ICar car) {
			car.run();
		}
	}
	public class Benz implements ICar{

		@Override
		public void run() {
			System.out.println(" benz running");
			
		}
		
	}
	public class Bmw implements ICar{

		@Override
		public void run() {
			System.out.println(" bmw running");
			
		}
	}
	
	public void main(String[] args){
		IDriver wanglei = new Driver();
		ICar benz = new Benz();
		wanglei.drive(benz);
	}

  依赖的三种写法:

1、构造函数传递依赖对象

public interface IDriver{
		public void drive();
	}
	
	public class Driver implements IDriver{
		private ICar mCar;
		
		public void Driver(ICar car){
			this.mCar = car;
		}

		@Override
		public void drive() {
			mCar.run();
		}
	}

  

2、set方法传递依赖对象

public interface IDriver{
		public void drive();
		public void setCar(ICar car);
	}
	
	public class Driver implements IDriver{
		private ICar mCar;

		@Override
		public void drive() {
			mCar.run();
		}

		@Override
		public void setCar(ICar car) {
			this.mCar = car;
			
		}
	}

  

3、接口声明依赖对象

依赖倒置原则

标签:

原文地址:http://www.cnblogs.com/wangqian-easy/p/4836215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!