📄 factory method2.cpp
字号:
//去掉了ShapeFactory的两个子类,改为由ShapeFactory直接负责实例的创建.
// ShapeFactory自己变成一个具体的创建器,直接用参数化的方法实现factoryMethod返回多种对象.
class ShapeFactory {
private: static Shape s;
ShapeFactory() {}
static Shape factoryMethod(String aName, String aType) {
if (aType.compareTo("square")==0)
return new Square(aName);
else if (aType.compareTo("circle")==0)
return new Circle(aName);
else throw new NoThisShape(aType);
}
// 在anOperation中定义Shape的一系列行为
static void anOperation(String aName, String aType) throws NoThisShape{
s = factoryMethod(aName, aType);
cout<<"The current shape is: " + s.name<<endl;
s.draw();
s.erase();
}
};
void main(){
ShapeFactory::anOperation("Shape one","circle");
ShapeFactory::anOperation("Shape two","square");
ShapeFactory::anOperation("Shape three", "delta");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -