使用工厂模式以前, 绘制每个图元时都要使用new操作符进行实例化, 具体如下:
public static void OnMouseDown(object sender, MouseEventArgs e)
{
NCControl ncControl = sender as NCControl;
startPoint = new Point(e.X, e.Y);
switch (ncControl.CurrentOperator)
{
case Operator.Line:
ncControl.CurrentShape = new Line(); //实例化
ncControl.CurrentShape.Pen = ncControl.CurrentPen;
break;
case Operator.Ellipse:
ncControl.CurrentShape = new Ellipse(); //实例化
ncControl.CurrentShape.Pen = ncControl.CurrentPen;
break;
default:
break;
}
}
{
NCControl ncControl = sender as NCControl;
startPoint = new Point(e.X, e.Y);
switch (ncControl.CurrentOperator)
{
case Operator.Line:
ncControl.CurrentShape = new Line(); //实例化
ncControl.CurrentShape.Pen = ncControl.CurrentPen;
break;
case Operator.Ellipse:
ncControl.CurrentShape = new Ellipse(); //实例化
ncControl.CurrentShape.Pen = ncControl.CurrentPen;
break;
default:
break;
}
}
结果是很不爽!!

用了工厂模式以后呢, 上面的代码就变成如下样子啦:
public static void OnMouseDown(object sender, MouseEventArgs e)
{
NCControl ncControl = sender as NCControl;
startPoint = new Point(e.X, e.Y);
//使用抽象工厂设计模式后,switch代码段就可以去掉了!
string shapename = ncControl.CurrentOperator.ToString();
ncControl.CurrentShape = ShapeFactory.CreateShape(shapename);
ncControl.CurrentShape.Pen = ncControl.CurrentPen;
}
{
NCControl ncControl = sender as NCControl;
startPoint = new Point(e.X, e.Y);
//使用抽象工厂设计模式后,switch代码段就可以去掉了!
string shapename = ncControl.CurrentOperator.ToString();
ncControl.CurrentShape = ShapeFactory.CreateShape(shapename);
ncControl.CurrentShape.Pen = ncControl.CurrentPen;
}
是不是很简洁呢。
这其中的奥秘也就在ShapeFactory抽象工厂类中:
public abstract class ShapeFactory
{
public static IShape CreateShape(string name)
{
try
{
string typename = "你的命名空间."+ name;
Type shapetype = Type.GetType(typename, true);
IShape shape = Activator.CreateInstance(shapetype) as IShape;
return shape;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return null;
}
}
{
public static IShape CreateShape(string name)
{
try
{
string typename = "你的命名空间."+ name;
Type shapetype = Type.GetType(typename, true);
IShape shape = Activator.CreateInstance(shapetype) as IShape;
return shape;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return null;
}
}
类继承关系如下:
IShape-->SimpleShape--> Line/Ellipse/....
如果您对工厂模式不熟,可以参考:
http://www.qqgb.com/Program/CCC/CCCSJ/Program_56488.html