单例模式和简单工厂模式小结
单例模式:该类只能有一个对象实例,所有构造函数和拷贝构造函数以及赋值函数都要在私有中。然后在public中设置一个static静态函数 调用的时候用类名Singleton::getInstance()得到唯一一个对象实例
代码简单如下:
class Sington { private: Sington(){}; Sington(const Sington& sington); //拷贝构造函数 可以不加 Sington& operator=(const Sington& sington); //赋值函数 可以不加 运算符重载 public: static Sington& getInstance() { Sington* sington = new Sington(); return *sington; } void test() { cout<<"sington test"<<endl; } };
Sington& b = Sington::getInstance();
b.test();
//简单工厂模式 enum TypeProduct { typeA, typeB, typeC }; class Product { public: virtual void show() = 0;//纯虚函数 }; class ProductA : public Product { public: void show() { cout<<"A show"<<endl; } }; class ProductB : public Product { public: void show() { cout<<"B show"<<endl; } }; class ProductC : public Product { public: void show() { cout<<"C show"<<endl; } }; class Factory { public: Product* createProduct(TypeProduct type) { switch (type) { case typeA: return new ProductA(); break; case typeB: return new ProductB(); break; case typeC: return new ProductC(); break; default: break; } return NULL; } };
int main() { Factory productFactory; Product* productA = productFactory.createProduct(typeA); Product* productB = productFactory.createProduct(typeB); Product* productC = productFactory.createProduct(typeC); productA->show(); productB->show(); productC->show(); if(productA) { delete productA; productA = NULL; } if(productB) { delete productB; productB = NULL; } if(productC) { delete productC; productC = NULL; } }测试结果如图所示: