实现singleton设计模式并在整个类中使用它



我有一个控制台应用程序,我在其中解决了一个算法。我在program.cs文件中有所有的逻辑,但后来我被要求实现面向对象的设计,并更多地使用concerne的分离。所以我开始把我的逻辑分成不同的类,但在program.cs中,我有4个全局变量,我会在逻辑中使用它们来求解算法。

现在我已经将这4个全局变量分离,并将它们放在一个类中。我需要的是使用这些字段,就像我在程序.cs中一样我需要在整个类和方法中使用这4个全局变量,并为它们分配不同的值。

我已经尝试实现Singleton设计模式,因为我认为这将适合我的情况,因为我只会实例化一次类,并且我会存储这些值,以便在不同的时刻使用它们,以及它们的特定值。

因此,基本上,我需要一个类只实例化一次,并在其他类中使用,但也需要像使用全局变量一样保留值。

这是我的代码

class cars.cs

public void ForbidenConfig(int number)
{
Collections c = new Collections();
Wheels3 w3 = Wheels3.GetInstance; // here I get the instance of the class
int k = 1;
Configurations[] block = new Configurations[number];
for (int i = number; i > 0; i--)
{
Console.Write("Test case " + k + ": ");
//bla bla bla another logic here

//below I want to add data to collections
w3.Collections.Add(block[k - 1]);
k++;
}
c.AddCollections(object1, object2);
}

现在我还有其他的类集合.cs,我有这个代码

public void AddCollections(CarsConfigurations config, CarsConfigurations previousConfig)
{
Cars w3 = Cars.GetInstance; // here I get the instance of the class
if (CheckConfiguration(config) == false)
{
config.SetPreviousState(previousConfig);
//below I also add data to another field of the singleton class
w3.AddCollections2.Add(config);
}
}

现在这是我的单重态

public void AddCollections(CarsConfigurations config, CarsConfigurations previousConfig)
{
Cars w3 = Cars.GetInstance; // here I get the instance of the class
if (CheckConfiguration(config) == false)
{
config.SetPreviousState(previousConfig);
w3.AddCollections.Add(config);
}
}

public sealed class Cars
{
private static List<CarsConfigurations> ConfigCollections = new List<CarsConfigurations>();
private static List<CarsConfigurations> ClosedStateCollections = new List<CarsConfigurations>();


private static Cars instance = null;
public static Cars GetInstance
{
get
{
if (instance == null)
instance = new Cars();
return instance;
}
}
private Cars()
{
List<CarsConfigurations> ConfigCollections = new List<CarsConfigurations>();
List<CarsConfigurations> ClosedStateCollections = new List<CarsConfigurations>();
}
public static void ConfigCollection()
{
return this.ConfigCollections; // this line gives me an error ofcourse,  Member 'Cars.ConfigCollections' cannot be accessed with an instance reference; qualify it with a type name instead 
} 

}

我能用Singleton设计模式实现我想要的目标吗。。?如果是,我该怎么办?还有别的办法吗?你们能帮帮我吗?我有任务要做,我真的没时间了!你能提出其他想法吗?

我真的非常感谢你的帮助。提前谢谢!

我被要求实现面向对象的设计

在这种情况下,一组美化的全局变量并不能解决这个问题。辛格尔顿设计模式有它的用途,但不是这样的。

相反,作为一个开始,将变量作为方法参数传递:

public void AddCollections(
CarsConfigurations config,
CarsConfigurations previousConfig,
Cars w3)
{
if (CheckConfiguration(config) == false)
{
config.SetPreviousState(previousConfig);
w3.AddCollections2.Add(config);
}
}

一旦你完成了这项工作,你可能需要考虑是否可以进行进一步的建模。例如,上面的方法同时具有Cars和两个CarsConfiguration对象。以某种方式将这两个类结合起来有意义吗?

最新更新