下面就来看一个Demo ,从这个Demo 中看出抽象工厂的优点
先来展现一下具体的类图
上面的类图呢,说明的是有两个具体工厂,一个是Linux 控件的制造,还有一个是Windows 控件的制造,
然后,有两个产品族,一个是WindowsTextBox 和LinuxTextBox 组成的TextBox 产品族,还有一个就是WindowsButton 和LinuxButton 组成的Button 产品族。
下面就来写类了
先来看工厂类吧
namespace AbstractFactory
{
public abstract class AbstractFactory
{
//在抽象工厂中,应该包含所有产品创建的抽象方法
public abstract Button CreateButton(); public abstract TextBox CreateTextBox(); }
}
namespace AbstractFactory
{
public class WindowsFactory:AbstractFactory {
public override Button CreateButton() {
return new WindowsButton();
}
public override TextBox CreateTextBox() {
return new WindowsTextBox();
}
}
}
namespace AbstractFactory
{
public class LinuxFactory:AbstractFactory
{
public override Button CreateButton() {
return new LinuxButton();
}
public override TextBox CreateTextBox() {
return new LinuxTextBox();
}
}
}
下面就给出所有的产品类
namespace AbstractFactory
{
public abstract class Button
{
public abstract void DisplayButton();
}
}
using System;
namespace AbstractFactory
{
class LinuxButton:Button
{
public override void DisplayButton()
{
Console.WriteLine("我的类型是:{0}",
this.GetType().ToString());
}
}
}
using System;
namespace AbstractFactory
{
class WindowsButton : Button
{
public override void DisplayButton()
{
Console.WriteLine("我的类型是:{0}",
this.GetType().ToString());
}
}
}
namespace AbstractFactory
{
public abstract class TextBox
{
public abstract void DisplayTextBox(); }
}
using System;
namespace AbstractFactory
{
class LinuxTextBox : TextBox
{
public override void DisplayTextBox()
{
Console.WriteLine("我的类型是:{0}",
this.GetType().ToString());
}
}
}
using System;
namespace AbstractFactory
{
class WindowsTextBox:TextBox
{
public override void DisplayTextBox()
{
Console.WriteLine("我的类型是:{0}",
this.GetType().ToString());
}
}
}
上面就是整个Demo 的类了,下面就是看一下Main 函数和效果了using System;
using AbstractFactory;
namespace AbstractFactoryTest
{
class Program
{
static void Main(string[] args)
{
AbstractFactory.AbstractFactory factory;
Button button;
TextBox textBox;
//Windows 下操作
factory = new WindowsFactory();
button = factory.CreateButton();
textBox = factory.CreateTextBox();
button.DisplayButton();
textBox.DisplayTextBox();
Console.WriteLine();
//Linux 下操作
factory = new LinuxFactory();
button = factory.CreateButton();
textBox = factory.CreateTextBox();
button.DisplayButton();
textBox.DisplayTextBox();
Console.ReadLine();
}
}
}
从上面Main 函数来看的话,如果你的系统本来是基于Linux 的话,你只需更改一行代码factory = new WindowsFactory();
即可实现将系统更改为Windows ,
抽象工厂在这种情况下是非常有用的,比如,如果要实现后台数据库从Oracle 转换到Sql Server,
则采用抽象工厂的思想实现是最好的。
下面总结一下抽象工厂的优缺点
首先,抽象工厂的话,其可以更加方便的实现交换一个产品系列,
就像上面的Demo 中可以轻易的实现从Linux 上转换为Windows,
同时,客户端代码中依赖的是抽象,而非具体的实现,
但是,抽象工厂也是有缺点的,其实这个缺点也很明显,那就是显得过于臃肿,
上面的Demo 尽管还只有两个产品族,类图就显得有些难看了,
如果产品族一多的话,那么总的类数是成几倍的增加,这样使整个结构变得过于复杂,
类的结构也会变得更为庞大。
尾声
上面呢,接连介绍了简单工厂,工厂方法,抽象工厂,整个工厂模式的介绍就到此告一段落了。