class Benz:IDrive
{
public void drive() {
Console.WriteLine("奔驰开始启动了...");
}
}
class Haval:IDrive
{
public void drive() {
Console.WriteLine("哈佛开始启动了");
}
}
class BMW:IDrive
{
public void drive() {
Console.WriteLine("宝马开始启动了...");
}
}
三.工厂类定义
class CarFactory
{
public static IDrive createCar(String name) {
switch (name) {
case "benz":
return new Benz();break;
case "bmw":
return new BMW(); break;
case "haval":
return new Haval(); break;
default:
return null;
}
}
}
四.测试类定义
//我们使用的都是直接new
//Benz bz = new Benz();
//Haval ha=new Haval();
Console.WriteLine("请输入您要选择的车:");
string name = Console.ReadLine();
Console.WriteLine(name+","+name.Length);
//使用接口来接受一下
IDrive car=Factory.createCar(name);
car.run();
Console.ReadLine();