接口的作用和使用实例(何为紧耦合和松耦合)
在介绍接口Interface的主要功能之前,我们先介绍一下什么是紧耦合
class Program
{
static void Main(string[] args)
{
var engine = new Engine();
var car = new Car(engine);
car.Run(3);
Console.WriteLine(car.Speed);
}
}
class Engine
{
public int RPM { get; private set; }
public void work(int gas)
{
this.RPM = 1000 * gas;
}
}
class Car
{
private Engine _engine;
public Car(Engine engine)
{
this._engine = engine;
}
public int Speed { get;private set; }
public void Run(int gas)
{
_engine.work(gas);
this.Speed = _engine.RPM / 100;
}
}
紧耦合的编程:
倘若Engine类出现错误,如误写为this.RPM = 0;
则在大项目中难以定位修改这个问题,因此引入接口减少耦合程度。
接口是一组契约,用来约束一组功能,这组功能的调用者是被约束的,被约束为只能调用这组接口里所规定的功能(接口里没包含的功能看不见也调用不了),而且调用者不用关心这些功能由谁提供,接口来保证这些功能都稳定可靠。
class Program
{
static void Main(string[] args)
{
var user = new User(new Iphone());
user.UsePhone();
}
}
interface IPhone
{
void Dail();
void PickUp();
void Send();
void Receive();
}
class User
{
private IPhone _phone;
public User(IPhone phone)
{
this._phone = phone;
}
public void UsePhone()
{
_phone.Dail();
_phone.Dail();
_phone.Dail();
}
}
class XiaoMiPhone:IPhone
{
public void Dail() { Console.WriteLine("Are U Ok?"); }
public void PickUp() { Console.WriteLine("Hello?"); }
public void Send() { Console.WriteLine("Think You!"); }
public void Receive() { Console.WriteLine("Think You Very Much!"); }
}
class Iphone : IPhone
{
public void Dail() { Console.WriteLine("Buy?"); }
public void PickUp() { Console.WriteLine("Buy??"); }
public void Send() { Console.WriteLine("Buy???"); }
public void Receive() { Console.WriteLine("Buy????"); }
}
}
通过接口只需要更改
var user = new User(new Iphone());
var user = new User(new XiaoMiPhone());
就可以换手机。
通过引入接口极大降低了耦合度,即为松耦合。