我有一个带有抽象工厂方法的类,如下所示:
public abstract class OpClass
{
public abstract IHou OperationInvoke(string opClass);
}
public class FactoryClass : OpClass
{
public override IHou OperationInvoke(string opClass)
{
if(opClass == "T")
{
//new Treasure();
}
}
}
具体的“宝藏”类是这样的:
public interface IHou
{
void Operation(Player p, List<Player> lstPlayers);
}
public sealed class Treasure : IHou
{
private static Treasure instance = null;
private static readonly object padlock = new object();
Treasure()
{
}
public static Treasure Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Treasure();
}
return instance;
}
}
}
public void Operation(Player p, List<Player> lstPlayers)
{
p.Points = p.Points + 200;
}
}
在我的主要方法中,我试图将其称为:
Main()
{
Player p = //Populate from db;
List<Player> players = //populate from db
OpClass c = new FactoryClass();
IHou output = c.OperationInvoke("T");
output.Operation(p, players);
}
但是我需要一个"Treasure" 类的实例,所以我想到了将普通的"Treasure" 类更改为单例类。
那么在这种情况下,如何创建 Treasure 类的单个实例并保留工厂模式?如果添加了 Treasure 、 House 、 Blocks 等具体类的数量,那么最好的解决方案是什么?
编辑:这里使用工厂模式是不是不合适,因为我的理解是如果我们有很多像这个 Treasure 中一样具有共同行为的类,再说一个类“House"被添加以不同的方式计算点,我将允许工厂决定调用哪个实例化。
最佳答案
你可以为此使用 Flyweight 模式,在这种模式中你将实例存储在缓存或字典中并从工厂返回它
借助如下所示的基于泛型的工厂实现,您无需添加更多案例,它将基于模板类型 T 创建类。您可以访问下面的文章链接,了解相同的实现之王。
public class FlyWeidhtFactory
{
Dictionary<string,IHou> dic = new Dictionary<string,IHou>();
public IHou OperationInvoke<T>(string opClass) where T: IHou
{
Type type = typeof(T);
string fullname = type.FullName;
if(!dic.Contains(fullname)
{
Object obj = Activator.CreateInstance(type);
dic[fullname] = (T)obj;
//no need of more cases
}
return dic[opClass];
}
}
pattern 确保您将创建许多对象,并且通过上述实现,您可以确保只会创建您的类的一个实例。无需选择单例模式。
让你的具体类内部密封
,所以它在你的程序集之外是不可见的。
以上只是根据您的问题提出的建议。
工厂和享元的文章:
关于c# - 在抽象工厂方法中调用单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50502441/