小编Hin*_*rik的帖子

工厂设计模式 - 为什么需要接口?

我开始研究不同的设计模式,现在我专注于工厂设计模式.我看了一些例子,youtube tuturials和博客,我得到了最多,但我仍然没有得到为什么接口是必要的.

官方定义是:

定义用于创建对象的接口,但让子类决定实例化哪个类.Factory Method允许类将实例化延迟到子类.

因此,界面似乎是工厂设计模式的重要组成部分,但是我发现在主方法中创建集合时实际的唯一原因.如果你不想要它,你可以删除它(看下面的代码,可能的地方),它仍然像计划的那样工作.

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, …
Run Code Online (Sandbox Code Playgroud)

c# design-patterns factory factory-pattern

6
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×1

design-patterns ×1

factory ×1

factory-pattern ×1