Osa*_*aHQ 3 c# dependencies design-patterns factory
在我的程序中,一些对象需要其他对象(依赖),而我正在使用Factory作为我的创建模式.
现在,我该如何解决一个简单的依赖问题?
这是我正在做的解决问题的一个例子.我想知道将所需对象发送到Create方法是不是非常错误.
//AbstractBackground
// - SpecialBackground
// - ImageBackground
// - NormalBackground
class Screen{
List<AbstractBackground> list;
Cursor cursor;
ContentManager content;
public void load(string[] backgroundTypes){
//is this okay? --------------->
AbstractBackground background = BackgroundFactory.Create(backgroundTypes[0], cursor, content);
list.add(background);
}
}
class BackgroundFactory{
static public AbstractBackground Create(string type, Cursor cursor, ContentManager content){
if( type.Equals("special") ){
return new SpecialBackground(cursor, content);
}
if( type.Equals("image") ){
return new ImageBackground(content);
}
if( type.Equals("normal") ){
return new NormalBackground();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它是功能性的,但是,如果添加更多类型,它可能会变得很麻烦.
根据我个人对简易工厂的偏好,实施将是:
enum BackgroundFactoryType
{
Special,
Image,
Normal,
}
static class BackgroundFactory{
static Dictionary<BackgroundFactoryType, Func<Cursor, ContentManager, AbstractBackground>> constructors;
static BackgroundFactory()
{
//initialize the constructor funcs
constructors = new Dictionary<BackgroundFactoryType, Func<Cursor, ContentManager, AbstractBackground>>();
constructors.Add(BackgroundFactoryType.Special, (cursor, content) => new SpecialBackground(cursor, content));
constructors.Add(BackgroundFactoryType.Image, (_, content) => new ImageBackground(content));
constructors.Add(BackgroundFactoryType.Normal, (_, __) => new NormalBackground());
}
static public AbstractBackground Create(BackgroundFactoryType type, Cursor cursor, ContentManager content)
{
if (!constructors.ContainsKey(type))
throw new ArgumentException("the type is bogus");
return constructors[type](cursor, content);
}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以简单地做:
static class BackgroundFactory{
static public AbstractBackground Create(BackgroundFactoryType type, Cursor cursor, ContentManager content)
{
switch (type)
{
case BackgroundFactoryType.Special:
return new SpecialBackground(cursor, content);
case BackgroundFactoryType.Image:
return new ImageBackground(content);
case BackgroundFactoryType.Normal:
return new NormalBackground();
default:
throw new ArgumentException("the type is bogus");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法的一个很好的副作用是,只需要一点工作就可以使这个东西配置驱动而不是硬编码.