工厂方法模式自己写的例子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testFactory
{
//抽象产品角色
public interface Car
{
void drive();
}
//具体产品角色
public class Benz : Car
{
public void drive()
{
Console.WriteLine("Driving Benz");
}
}
public class Bmw : Car
{
public void drive()
{
Console.WriteLine("Driving Bmw");
}
}
//抽象工厂
public interface Factory
{
Car driverCar();
}
//具体工厂类角色
public class DriverBenz : Factory
{
public Car driverCar()
{
return new Benz();
}
}
public class DriverBmw : Factory
{
public Car driverCar()
{
return new Bmw();
}
}
class Program
{
static void Main(string[] args)
{
Factory driver = new DriverBenz();
Car car = new Benz();
car.drive();
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testFactory
{
//抽象产品角色
public interface Car
{
void drive();
}
//具体产品角色
public class Benz : Car
{
public void drive()
{
Console.WriteLine("Driving Benz");
}
}
public class Bmw : Car
{
public void drive()
{
Console.WriteLine("Driving Bmw");
}
}
//抽象工厂
public interface Factory
{
Car driverCar();
}
//具体工厂类角色
public class DriverBenz : Factory
{
public Car driverCar()
{
return new Benz();
}
}
public class DriverBmw : Factory
{
public Car driverCar()
{
return new Bmw();
}
}
class Program
{
static void Main(string[] args)
{
Factory driver = new DriverBenz();
Car car = new Benz();
car.drive();
Console.ReadLine();
}
}
}