示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var driver1 = new Driver(new Car());
driver1.Drive();
var driver2 = new Driver(new LightTank());
driver2.Drive();
}
}
class Driver
{
private IVehicle _vehicle;
public Driver(IVehicle vehicle)
{
_vehicle = vehicle;
}
public void Drive()
{
_vehicle.Run();
}
}
interface IVehicle
{
void Run();
}
class Car:IVehicle
{
public void Run()
{
Console.WriteLine("Car is running...");
}
}
class Truck : IVehicle
{
public void Run()
{
Console.WriteLine("Truck is running...");
}
}
interface IWeapon
{
void Fire();
}
interface ITank:IVehicle,IWeapon
{
}
class LightTank : ITank
{
public void Run()
{
Console.WriteLine("Light Tank run ...");
}
public void Fire()
{
Console.WriteLine("Light Boom...");
}
}
class MediumTank : ITank
{
public void Run()
{
Console.WriteLine("Medium Tank run ...");
}
public void Fire()
{
Console.WriteLine("Medium Boom...");
}
}
class HeavyTank : ITank
{
public void Run()
{
Console.WriteLine("Heavy Tank run ...");
}
public void Fire()
{
Console.WriteLine("Heavy Boom...");
}
}
}
结果: