Code
using System;
using System.Collections.Generic;
using System.Text;
namespace Learning.DesignPattern
{
//简单工厂模式(Simple Factory)
//产品接口ICar
public interface ICar
{
void Drive();
}
//具体的产品类实现ICar接口
public class HongQi : ICar
{
public void Drive()
{
Console.WriteLine("The driver driving the HongQi!");
}
}
public class DaZhong : ICar
{
public void Drive()
{
Console.WriteLine("The driver driving the DaZhong!");
}
}
//工厂类:
public class CarFactory
{
public static ICar DriveCar(string carName)
{
if (carName == "HongQi")
{
return new HongQi();
}
else if (carName == "DaZhong")
{
return new DaZhong();
}
else
{
return null;
}
}
}
//调用该工厂类,执行具体产品方法:
public class Program
{
public static void Main()
{
string carName = "HongQi";
Console.Write("请输入车名:");
Console.Write("+>");
carName = Console.ReadLine();
try
{
CarFactory.DriveCar(carName).Drive();
}
catch
{
Console.Write("您输入的车名无效!");
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Learning.DesignPattern
{
//简单工厂模式(Simple Factory)
//产品接口ICar
public interface ICar
{
void Drive();
}
//具体的产品类实现ICar接口
public class HongQi : ICar
{
public void Drive()
{
Console.WriteLine("The driver driving the HongQi!");
}
}
public class DaZhong : ICar
{
public void Drive()
{
Console.WriteLine("The driver driving the DaZhong!");
}
}
//工厂类:
public class CarFactory
{
public static ICar DriveCar(string carName)
{
if (carName == "HongQi")
{
return new HongQi();
}
else if (carName == "DaZhong")
{
return new DaZhong();
}
else
{
return null;
}
}
}
//调用该工厂类,执行具体产品方法:
public class Program
{
public static void Main()
{
string carName = "HongQi";
Console.Write("请输入车名:");
Console.Write("+>");
carName = Console.ReadLine();
try
{
CarFactory.DriveCar(carName).Drive();
}
catch
{
Console.Write("您输入的车名无效!");
}
Console.ReadLine();
}
}
}