接口容易被正确使用,不易被误用
c++简单工厂模式时,初级实现为ITest* CreateTestOld(), 然后用户负责释放返回的对象。如果忘记释放就会造成memory leak,所以在设计工厂接口时就应屏蔽这个潜在的问题,这时就可以用智能指针shared_ptr<ITest> CreateTest(),由他负责对象资源的管理,而对客户端的使用来说更简洁了。
1 #include "stdafx.h" 2 #include <memory> 3 #include <iostream> 4 using namespace std; 5 6 class ITest 7 { 8 public: 9 virtual void Func() = 0; 10 virtual ~ITest(){} 11 }; 12 13 class Test : public ITest 14 { 15 public: 16 void Func() override 17 { 18 cout << "Test::Func" << endl; 19 } 20 Test() 21 { 22 cout << "Test ctor!" << endl; 23 } 24 ~Test() 25 { 26 cout << "Test destroy!" << endl; 27 } 28 29 }; 30 31 class Factory 32 { 33 public: 34 static shared_ptr<ITest> CreateTest() 35 { 36 return shared_ptr<ITest>(new Test); 37 } 38 39 static ITest* CreateTestOld() 40 { 41 return new Test; 42 } 43 }; 44 45 46 int _tmain(int argc, _TCHAR* argv[]) 47 { 48 auto ptr2 = Factory::CreateTestOld(); 49 ptr2->Func(); 50 delete ptr2; 51 52 auto ptr = Factory::CreateTest(); 53 ptr->Func(); 54 55 return 0; 56 }