Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
为一个产品族提供了统一的创建接口。当需要这个产品族的某一系列的时候,可以从抽象工厂中选出相应的系列创建一个具体的工厂类。
public interface IButton {
void Paint();
}
public interface IGuiFactory {
IButton CreateButton();
}
public class OsxButton : IButton {
public void Paint() {
Console.WriteLine("I'm an OSXButton");
}
}
public class WinButton : IButton {
public void Paint() {
Console.WriteLine("I'm a WinButton");
}
}
public class OsxFactory : IGuiFactory {
IButton IGuiFactory.CreateButton() {
return new OsxButton();
}
}
public class WinFactory : IGuiFactory {
IButton IGuiFactory.CreateButton() {
return new WinButton();
}
}
public class Application {
public Application(IGuiFactory factory) {
var button = factory.CreateButton();
button.Paint();
}
}
public class ApplicationRunner {
static IGuiFactory CreateOsSpecificFactory() {
var sysType = ConfigurationManager.AppSettings["OS_TYPE"] ?? "Win";
if (sysType == "Win") {
return new WinFactory();
}
return new OsxFactory();
}
static void Main(string[] args) {
new Application(CreateOsSpecificFactory());
Console.ReadKey();
}
}