控制台应用程序中的工厂设计模式实现

问题描述

我是编程和通过在线内容学习的新手,现在的你们!我正在阅读有关工厂设计模式的内容并尝试在非常基本的项目中实施,我有一个解决方案,其中有两个项目,一个项目包含接口,另一个包含实现,我已经阅读了有关工厂的信息,但不幸的是,我不知道如何在我的项目中实现,在一个项目中,我有 2 个接口 IBasicCars 和 ILuxuryCars,IluxuryCars 实现 IBasicCars 然后在第二个项目中我有一个类继承自 ILuxuryCars 并实现其所有方法和 IBasicCars 方法属性,这是我的代码那个班级。

    public class LuxuryCars : ILuxuryCar
{            
    

    private string _color { get; set; }
    public string Color
    {
        get
        {
            return _color;
        }
        set
        {
            _color = value;
        }
    }

    private int _model { get; set; }
    public int Model
    {
        get
        {
            return _model;
        }
        set
        {
            _model = value;
        }
    }


    private string _make { get; set; }
    public string Make
    {
        get
        {
            return _make;
        }
        set
        {
            _make = value;
        }
    }

    public void Break()
    {
        Console.WriteLine("This is the basic function of all cars !!!");
    }

    public void CruiseControl()
    {
        Console.WriteLine("This is the luxury feature for luxury cars !!!");
    }

    public void Drive()
    {
        Console.WriteLine("This is the basic function of all cars !!!");
    }

    public void Navigation()
    {
        Console.WriteLine("This is the luxury feature for luxury cars !!!");
    }

    public void Park()
    {
        Console.WriteLine("This is the basic function of all cars !!!");
    }
}

现在我在那个项目中有另一个“FactoryObject”类,它现在什么都没有,有人可以告诉我我要实现工厂设计模式吗?

这就是我在主方法调用这些方法的方式

static void Main(string[] args)
    {
        
        ILuxuryCar lc = new LuxuryCars();


        lc.Color = "Black";
        lc.Make = "Honda";
        lc.Model = 2007;


        Console.WriteLine("Car color is: {0} Made by: {1} Model is: {2}",lc.Color,lc.Make,lc.Model);
        lc.Navigation();
        lc.CruiseControl();
        lc.Break();
        lc.Drive();
        lc.Park();

        Console.WriteLine();

        IBasicCar b = new LuxuryCars();

        b.Color = "Red";
        b.Make = "Alto";
        b.Model = 2019;


        Console.WriteLine("Car color is: {0} Made by: {1} Model is: {2}",lc.Model);
        lc.Break();
        lc.Drive();
        lc.Park();



        Console.ReadLine();



    }

解决方法

一个非常简单的工厂可能是

public interface ICarFactory{
     ICar Create();
}
public class BasicCarFactory : ICarFactory{
    public ICar Create() => new BasicCar();
}
public class LuxuryCarFactory : ICarFactory{
    public ICar Create() => new LuxuryCar();
}

这使得创建汽车变得更加复杂,但重要的是需要创建新汽车对象的组件可以在不知道创建什么样的汽车的情况下这样做。

例如,您可以在启动时检查许可证,并根据许可证创建不同的工厂,您将其交给所有其他组件。这样一来,您就可以在一个地方进行许可检查,而不是分散到不同的组件上。

在简单的情况下,您可能不需要单独的界面,Func<ICar> 可能就足够了。