C# 桥接模式(Bridge)
理解:当有两个变化点在同时变化时使用该模式,例如("人"<中国人、美国人、日本人> 驾驶 "车"<自行车、汽车、火车>)
代码:
using System.Windows.Forms;
namespace DesignMode.Bridge
{
//抽象车类
public abstract class Vehicle
{
public abstract void Run();
}
public class Bike : Vehicle
{
public override void Run()
{
MessageBox.Show("自行车行驶中....");
}
}
public class Car : Vehicle
{
public override void Run()
{
MessageBox.Show("小汽车行驶中....");
}
}
public class Train : Vehicle
{
public override void Run()
{
MessageBox.Show("火车行驶中....");
}
}
//抽象人类
public abstract class People
{
protected Vehicle _vehicle;
public void SetVehicle(Vehicle vehicle)
{
_vehicle = vehicle;
}
public abstract void Drive();
}
public class Chinese : People
{
public override void Drive()
{
MessageBox.Show("中国人:");
_vehicle.Run();
}
}
public class American : People
{
public override void Drive()
{
MessageBox.Show("美国人:");
_vehicle.Run();
}
}
public class Japanese : People
{
public override void Drive()
{
MessageBox.Show("日本人:");
_vehicle.Run();
}
}}
namespace DesignMode.Bridge
{
//抽象车类
public abstract class Vehicle
{
public abstract void Run();
}
public class Bike : Vehicle
{
public override void Run()
{
MessageBox.Show("自行车行驶中....");
}
}
public class Car : Vehicle
{
public override void Run()
{
MessageBox.Show("小汽车行驶中....");
}
}
public class Train : Vehicle
{
public override void Run()
{
MessageBox.Show("火车行驶中....");
}
}
//抽象人类
public abstract class People
{
protected Vehicle _vehicle;
public void SetVehicle(Vehicle vehicle)
{
_vehicle = vehicle;
}
public abstract void Drive();
}
public class Chinese : People
{
public override void Drive()
{
MessageBox.Show("中国人:");
_vehicle.Run();
}
}
public class American : People
{
public override void Drive()
{
MessageBox.Show("美国人:");
_vehicle.Run();
}
}
public class Japanese : People
{
public override void Drive()
{
MessageBox.Show("日本人:");
_vehicle.Run();
}
}}
客户端代码:
private void btn_Bridge_Click(object sender, EventArgs e)
{
//先把车搬出来
Bike bike = new Bike();
Car car = new Car();
Train train = new Train();
//下面任意组合,该模式最大的好处就是把组合放在客户端,当要添加车类型时不用去改以前的类
//日本人开火车
Japanese japanese = new Japanese();
japanese.SetVehicle(train);
japanese.Drive();
//日本人开自行车
japanese.SetVehicle(bike);
japanese.Drive();
//中国人开汽车
Chinese chinese = new Chinese();
chinese.SetVehicle(car);
chinese.Drive();
//美国人开自行车
American american = new American();
american.SetVehicle(bike);
american.Drive(); }
{
//先把车搬出来
Bike bike = new Bike();
Car car = new Car();
Train train = new Train();
//下面任意组合,该模式最大的好处就是把组合放在客户端,当要添加车类型时不用去改以前的类
//日本人开火车
Japanese japanese = new Japanese();
japanese.SetVehicle(train);
japanese.Drive();
//日本人开自行车
japanese.SetVehicle(bike);
japanese.Drive();
//中国人开汽车
Chinese chinese = new Chinese();
chinese.SetVehicle(car);
chinese.Drive();
//美国人开自行车
American american = new American();
american.SetVehicle(bike);
american.Drive(); }