gpt4 book ai didi

c# - 对象缓存设计模式

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

我想知道是否有一种不那么痛苦的方法来编写如下内容:

public class Company {
// CEO, Programmer, and Janitor all inherit from an Employee class.
private CEO _CacheCEO {get;} = CEOFactory.NewCEO();
private Programmer _CacheJavaProgrammer {get;} = ProgrammerFactory.NewJavaProgrammer();
private Programmer _CacheIOSProgrammer {get;} = ProgrammerFactory.NewIOSProgrammer();
private Janitor _CacheJanitor {get;} = JanitorFactory.NewJanitor();
// etc.
public IEnumerable<Employee> GetEmployeesPresentToday() {
List<Employee> r = new List<Employee>();
if (ExternalCondition1) { // value of the condition may differ on successive calls to this method
r.Add(this._CacheCEO);
};
if (ExternalCondition2) { // all conditions are external to the Company class, and it does not get notified of changes.
r.Add(this._CacheJavaProgrammer);
}
if (ExternalCondition3) {
r.Add(this._CacheIOSProgrammer);
}
if (ExternalCondition4) {
r.Add(this._CacheJanitor);
}
// etc.
return r;
}

这里让我烦恼的部分是所有私有(private) IVar。如果我有(比方说)30 名不同的员工,那就很费力了。有没有办法避免为每个员工使用单独的 ivar?

除了通过 GetEmployeesPresentToday() 方法之外,我不太可能需要访问员工对象。换句话说,我不希望任何代码询问“谁是你的 CEO?”等等。

但是,重要的是,如果对 GetEmployeesPresentToday() 进行了两次不同的调用,并且上述代码中的 Condition1 每次都为真,那么每个列表中应该出现相同的 CEO 对象。

最佳答案

这是一个可能的答案。但是,我不确定它比问题中的代码好还是坏。

public class Company {
private Dictionary<string, Employee> _CacheEmployees { get;} = new Dictionary<string, Employee>();

public Employee GetEmployee(string key, Func<Employee> factory) {
// Existence of this method is not really annoying as it only has to be written once.
private Dictionary<string, Employee> cache = this._CacheEmployees;
Employee r = null;
if (cache.ContainsKey(key)) {
r = cache[key];
}
if (r == null) {
r = factory();
cache[key] = r;
}
return r;
}

public IEnumerable<Employee> GetEmployeesPresentToday() {
// still somewhat messy, but perhaps better than the question code.
List<Employee> r = new List<Employee>();
if (ExternalCondition1) { // value of the condition may differ on successive calls to this method
r.Add(this.GetEmployee("CEO", CEOFactory.NewCEO));
};
if (ExternalCondition2) { // all conditions are external to the Company class, and it does not get notified of changes.
r.Add(this.GetEmployee("Java Programmer", ProgrammerFactory.NewJavaProgrammer));
}
if (ExternalCondition3) {
r.Add(this.GetEmployee("IOS Programmer", ProgrammerFactory.NewIOSProgrammer));
}
if (ExternalCondition4) {
r.Add(this.GetEmployee("Janitor", JanitorFactory.NewJanitor));
}
// etc.
return r;
}
}

关于c# - 对象缓存设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30343320/

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