factory method2.cpp
来自「C++课件,很好用的,帮助大家学习C++.」· C++ 代码 · 共 32 行
CPP
32 行
//去掉了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 + =
减小字号Ctrl + -
显示快捷键?