名称 | Abstract Factory |
结构 | |
意图 | 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 |
适用性 | - 一个系统要独立于它的产品的创建、组合和表示时。
- 一个系统要由多个产品系列中的一个来配置时。
- 当你要强调一系列相关的产品对象的设计以便进行联合使用时。
- 当你提供一个产品类库,而只想显示它们的接口而不是实现时。
|
namespace AbstractFactory
{
public abstract class AbstractControlFactory
{
abstract public AbstractTextBox CreateTextBox();
abstract public AbstractButton CreateButton();
}
public class ControlFactoryXP : AbstractControlFactory
{
public override AbstractTextBox CreateTextBox()
{
return new TextBoxXP();
}
public override AbstractButton CreateButton()
{
return new ButtonXP();
}
}
public class ControlFactoryVista : AbstractControlFactory
{
public override AbstractTextBox CreateTextBox()
{
return new TextBoxVista();
}
public override AbstractButton CreateButton()
{
return new ButtonVista();
}
}
}
namespace AbstractFactory
{
public abstract class AbstractButton
{
public abstract void Show();
}
public class ButtonXP : AbstractButton
{
public ButtonXP()
{
//Console.WriteLine("XP style Button created!");
}
public override void Show()
{
Console.WriteLine("This is XP style Button");
}
}
public class ButtonVista : AbstractButton
{
public ButtonVista()
{
//Console.WriteLine("Vista style Button created!");
}
public override void Show()
{
Console.WriteLine("This is Vista style Button");
}
}
}
namespace AbstractFactory
{
public abstract class AbstractTextBox
{
public abstract void Show();
}
public class TextBoxXP : AbstractTextBox
{
//public TextBoxXP()
//{
//}
public override void Show()
{
Console.WriteLine("This is XP style TextBox");
}
}
public class TextBoxVista : AbstractTextBox
{
public override void Show()
{
Console.WriteLine("This is Vista style TextBox");
}
}
}
namespace AbstractFactory
{
public class ControlApp
{
private AbstractButton button;
private AbstractTextBox textbox;
public ControlApp(AbstractControlFactory factory)
{
button = factory.CreateButton();
textbox = factory.CreateTextBox();
}
// Methods
public void Show()
{
button.Show();
textbox.Show();
}
}
class Client
{
static void Main(string[] args)
{
AbstractControlFactory FactoryXP = new ControlFactoryXP();
ControlApp appXP = new ControlApp(FactoryXP);
appXP.Show();
AbstractControlFactory FactoryVista = new ControlFactoryVista();
ControlApp appVista= new ControlApp(FactoryVista);
appVista.Show();
}
}