gpt4 book ai didi

c# - 单例:两全其美(想实例化类)

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:15 26 4
gpt4 key购买 nike

使用这段代码:

public class MyClass
{
public int Number;

private static MyClass myClass;

...

public MyClass GetInstance()
{
...

return myClass;
}
}

有没有一种方法可以同时支持以下两种说法?

MyClass.Number = 5;

其中 MyClass 检索用于存储 Number 值的静态类

MyClass myLocalClass = new MyClass();

或者脱离 Singleton 设计模式的替代方案,因为我也希望能够创建一个实例。

感谢您的关注!

最佳答案

您正在寻找的是 MonoState图案。我将引用 Robert C. Martin 的 C# 中的敏捷原则、模式和实践

The MONOSTATE pattern is another way to achieve singularity. It works through a completely different mechanism.

The first test function simply describes an object whose x variable can be set and retrieved. But the second test case shows that two instances of the same class behave as though they were one. If you set the x variable on one instance to a particular value, you can retrieve that value by getting the x variable of a different instance. It's as hough the two instances are simply different names for the same object.

因此您可以实例化 2 个或更多类,但它们都将共享相同的值。

下面是一个实现的例子:

public class Monostate
{
private static int itsX;

public int X
{
get { return itsX; }
set { itsX = value; }
}
}

还有测试,所以你可以看到它是如何使用的:

using NUnit.Framework;

[TestFixture]
public class TestMonostate
{
[Test]
public void TestInstance()
{
Monostate m = new Monostate();
for (int x = 0; x < 10; x++)
{
m.X = x;
Assert.AreEqual(x, m.X);
}
}
[Test]
public void TestInstancesBehaveAsOne()
{
Monostate m1 = new Monostate();
Monostate m2 = new Monostate();
for (int x = 0; x < 10; x++)
{
m1.X = x;
Assert.AreEqual(x, m2.X);
}
}
}

关于c# - 单例:两全其美(想实例化类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23305350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com