mercredi 20 mai 2015

Object caching design pattern

I am wondering if there is a less painful way to write something like the following:

public class Company {
  // CEO, Programmer, and Janitor all inherit from an Employee class.
  private CEO _CacheCEO {get;} = CEOFactory.NewCEO();
  private Programmer _CacheProgrammer {get;} = ProgrammerFactory.NewProgrammer();
  private Janitor _CacheJanitor {get;} = JanitorFactory.NewJanitor();
  // etc.
  public IEnumerable<Employee> GetEmployeesPresentToday() {
    List<Employee> r = new List<Employee>();
    if (Condition1) {   // value of the condition may differ on successive calls to this method
      r.Add(this._CacheCEO);
    };
    if (Condition2) {
      r.Add(this._CacheProgrammer);
    }
    if (Condition3) {
      r.Add(this._CacheJanitor);
    }
    // etc.
  }

The part that bugs me here is all the private IVars. If I have (say) 30 different employees, it gets laborious. Is there a way to avoid having a separate ivar for each employee?

I am not likely to need any access to the employee objects, other than through the GetEmployeesPresentToday() method. In other words, I do not expect any code to be asking "Who is your CEO?" or the like.

However, it is important that if two different calls are made to GetEmployeesPresentToday(), and Condition1 in the above code is true each time, then the same CEO object should appear in each list.

Aucun commentaire:

Enregistrer un commentaire