考虑下面的示例代码,其中包含一个类库设计和一个使用该库的可执行程序。
namespace AppLib
{
/// <summary>
/// Entry point for library. Stage manages all the actors in the logic.
/// </summary>
class StageApp
{
/// <summary>
/// Setting that is looked up by different actors
/// </summary>
public int SharedSetting { get; set; }
/// <summary>
/// Stage managing actors with app logic
/// </summary>
public IEnumerable<Actor> Actors { get { return m_actors.Where(x => x.Execute() > 40).ToArray(); } }
private List<Actor> m_actors = new List<Actor>();
}
/// <summary>
/// An object on the stage. Refers to stage (shared)settings and execute depending on the settings.
/// Hence actor should have reference to stage
/// </summary>
class Actor
{
private StageApp m_StageApp;
private int m_Property;
/// <summary>
/// An actor that needs to refer to stage to know what behavior to execute
/// </summary>
/// <param name="stage"></param>
public Actor(StageApp stage)
{
m_StageApp = stage;
m_Property = new Random().Next();
}
/// <summary>
/// Execute according to stage settings
/// </summary>
/// <returns></returns>
public int Execute()
{
return m_StageApp.SharedSetting * m_Property;
}
}
}
namespace AppExe
{
using AppLib;
class Program
{
static void Main(string[] args)
{
StageApp app = new StageApp();
app.SharedSetting = 5;
// Question: How to add actor to stage?
foreach (var actor in app.Actors)
Console.WriteLine(actor.Execute());
}
}
}
问题
Stage
并且Actor
有循环依赖,对我来说似乎很糟糕。例如,我们应该如何将演员添加到舞台?
如果我让用户自己创建新Actor()
的,那么他们必须继续提供Stage
.
如果我给Actor()
一个内部构造函数并创建Stage
一个工厂,那么我会失去一些让用户进行继承Actor
的灵活性。
如果我做Stage
一个单例,那么我只能有一组SharedSetting
. Stage
如果用户在他的 中想要多个AppExe
,则无法完成。
无论如何要重新设计架构以避免上述问题?