RAII
Resource Acquisition Is Initialization.
Resource acquired in constructor, released in destructor.
Ex: unique_ptr, shared_ptr, scoped_lock, open file in constructor, close in destructor.
Items constructed on the stack or items with auto-lifetime management (smart pointers etc..)
RAII addresses which aspect of C++?
Exceptions.
Dependency Injection
Inject via constructor arguments the resources a class depends on.
So the creator of Foo managed the creation and insertion of Foo’s dependencies.
Allows easy mocking, testing etc…
Factory Method works with this.
TDD
Test Driven Development.
Singleton Pattern C++ Implementation
class S
{
public:
// public getter returning single static instance
static S& getinstance()
{
static S instance;
return S;
}
private:
// private constructor, copy constructor & assignment
S(){}
S(S const&);
void operator=(S const&);
public:
// public deleted functions (good style)
s(S const&) = delete;
void operator=(S const&) = delete;Singleton Pattern
Single instance in system.
Hide constructor so only accessible by itself.
Static (globally accessible) method to get instance.
Adapter Pattern
Make class/interface compatible with another class or interface. Adapter class can own adaptee class and make calls. ex: Lm75Ctrl and Lm75CtrlAdapter - just extends the interface of Lm75Ctrl to implement ITempSensor.
Factory Method/Abstract Factory Pattern
Class or code doesn’t need to know HOW to create objects - or even what kind it will get.
Just calls factory::create_x().