public abstract class AbstractFactory
{
public new string GetType()
{
return "AbstractFactory";
}
public virtual string GetName()
{
return "AbstractFactory";
}
public string GetId()
{
return "AbstractFactory";
}
public abstract Shape GetShape(string shape);
public abstract Color GetColor(string color);
}
public class ShapeFactory : AbstractFactory
{
public new string GetType()
{
return "ShapeFactory";
}
public override string GetName()
{
return "ShapeFactory";
}
public new string GetId()
{
return "ShapeFactory";
}
public override Shape GetShape(string shape)
{
if (shape == null)
{
return null;
}
if (shape.Equals("CIRCLE"))
{
return new Circle();
}
else if (shape.Equals("RECTANGLE"))
{
return new Rectangle();
}
else if (shape.Equals("SQUARE"))
{
return new Square();
}
return null;
}
public override Color GetColor(string color)
{
return null;
}
}
static void Main(string[] args)
{
AbstractFactory factory = FactoryProducer.GetFactory("SHAPE");
string type = factory.GetType();
string name = factory.GetName();
string id = (factory as ShapeFactory).GetId();
Console.WriteLine(type + " " + name + " " + id);
Shape shape1 = factory.GetShape("RECTANGLE");
shape1.draw();
Console.ReadKey();
}
输出结果如下
总结:使用了override进行重写的方法,都调用子类的方法。
未使用override进行重写的方法,调用父类的实体方法。