【发布时间】:2023-03-23 20:34:01
【问题描述】:
在我的程序中,一些对象需要其他对象(依赖),我使用 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();
}
}
}
【问题讨论】:
-
为什么会出错?不是。
-
我想知道这一点,因为我对现实生活中的工厂模式没有太多经验。
标签: c# design-patterns dependencies factory