【发布时间】:2013-12-22 12:19:05
【问题描述】:
我开始研究不同的设计模式,现在我专注于工厂设计模式。我查看了一些示例、youtube tuturials 和博客,我得到的最多,但我仍然不明白为什么需要一个界面。
官方定义是:
定义创建对象的接口,但让子类决定 要实例化哪个类。工厂方法让一个类延迟 实例化到子类。
所以接口似乎是工厂设计模式的重要组成部分,但我发现它实用的唯一原因是你在 main 方法中创建一个集合。如果你不想这样,你可以删除它(看看下面的代码,如果可能的话)它仍然像计划的那样工作。
using System;
using System.Collections.Generic;
using System.Collections;
namespace FactoryDesignPattern
{
class Program
{
static void Main(string[] args)
{
var FordFiestaFactory = new FordFiestaFactory();
var FordFiesta = FordFiestaFactory.CreateCar("Blue");
Console.WriteLine("Brand: {0} \nModel: {1} \nColor: {2}", FordFiesta.Make, FordFiesta.Model, FordFiesta.Color);
Console.WriteLine();
//Inserted this later. Using a collection requires the Interface to be there.
List<ICreateCars> Cars = new List<ICreateCars>();
Cars.Add(new FordFiestaFactory());
Cars.Add(new BMWX5Factory());
foreach (var Car in Cars)
{
var ProductCar = Car.CreateCar("Red");
Console.WriteLine("Brand: {0} \nModel: {1} \nColor: {2}", ProductCar.Make, ProductCar.Model, ProductCar.Color);
Console.WriteLine();
}
Console.ReadKey();
}
}
public abstract class Car
{
public string Make { get; set; }
public string Model { get; set; }
public string EngineSize { get; set; }
public string Color { get; set; }
}
public class FordFiesta : Car
{
public FordFiesta()
{
Make = "Ford";
Model = "Fiesta";
EngineSize = "1.1";
}
}
public class BMWX5 : Car
{
public BMWX5()
{
Make = "BMW";
Model = "X5";
EngineSize = "2.1";
}
}
public interface ICreateCars
{
Car CreateCar(string color);
}
class FordFiestaFactory : ICreateCars
{
public Car CreateCar(string color)
{
return new FordFiesta() { Color = color };
}
}
class BMWX5Factory : ICreateCars
{
public Car CreateCar(string color)
{
return new BMWX5(){ Color = color };
}
}
}
那么为什么我需要那个接口呢?我阅读了多个抽象的解释,但我没有明白,所以我更喜欢实用的答案。
提前致谢!
【问题讨论】:
-
这个上下文中的接口一般有“接口”的字面意思..不是.NET意义上的接口。
标签: c# design-patterns factory factory-pattern