Design Patterns
Singleton Pattern
- Description: Ensures a class has only one instance and provides a global access point.
- Usage: Global configuration, logging, etc.
- Example:
class Singleton {
private:
static Singleton* _instance;
Singleton() {} // Private constructor
public:
static Singleton* getInstance() {
if (_instance == nullptr) {
_instance = new Singleton();
}
return _instance;
}
};
Singleton* Singleton::_instance = nullptr;
Factory Method Pattern
- Description: Defines an interface for creating product objects, letting subclasses decide which class to instantiate.
- Usage: Creating complex objects.
- Example:
class Product {};
class ConcreteProduct : public Product {};
class Creator {
public:
virtual Product* factoryMethod() = 0;
};
class ConcreteCreator : public Creator {
public:
Product* factoryMethod() override {
return new ConcreteProduct();
}
};
Abstract Factory Pattern
- Description: Provides an interface for creating families of related or dependent objects.
- Usage: Creating a series of related or dependent objects.
- Example:
class AbstractFactory {
public:
virtual AbstractProductA* createProductA() = 0;
virtual AbstractProductB* createProductB() = 0;
};
class ConcreteFactory1 : public AbstractFactory {
public:
AbstractProductA* createProductA() override {
return new ConcreteProductA1();
}
AbstractProductB* createProductB() override {
return new ConcreteProductB1();
}
};
Builder Pattern
- Description: Separates the construction of a complex object from its representation.
- Usage: Creating complex objects.
- Example:
class Director {
private:
Builder* builder;
public:
void setBuilder(Builder* b) { builder = b; }
void construct() {
builder->buildPartA();
builder->buildPartB();
}
};
class Builder {
public:
virtual void buildPartA() = 0;
virtual void buildPartB() = 0;
virtual Product* getResult() = 0;
};
class ConcreteBuilder : public Builder {
private:
Product* product;
public:
void buildPartA() override {
product->setPartA("Part A");
}
void buildPartB() override {
product->setPartB("Part B");
}
Product* getResult() override {
return product;
}
};
Prototype Pattern
- Description: Specifies the kinds of objects to create using a prototypical instance, and creates new objects by copying this prototype.
- Usage: Cloning objects.
- Example:
class Prototype {
public:
virtual Prototype* clone() const = 0;
};
class ConcretePrototype : public Prototype {
public:
Prototype* clone() const override {
return new ConcretePrototype(*this);
}
};
Adapter Pattern
- Description: Converts the interface of a class into another interface that clients expect.
- Usage: Compatibility between different interfaces.
- Example:
class Target {
public:
virtual void request() = 0;
};
class Adaptee {
public:
void specificRequest() {
std::cout << "Adaptee's specific request." << std::endl;
}
};
class Adapter : public Target {
private:
Adaptee* adaptee;
public:
Adapter(Adaptee* a) : adaptee(a) {}
void request() override {
adaptee->specificRequest();
}
};
Bridge Pattern
- Description: Decouples abstraction from its implementation so that the two can vary independently.
- Usage: Decoupling interface and implementation.
- Example:
class Implementor {
public:
virtual void operationImpl() = 0;
};
class ConcreteImplementorA : public Implementor {
public:
void operationImpl() override {
std::cout << "ConcreteImplementorA operation." << std::endl;
}
};
class Abstraction {
protected:
Implementor* implementor;
public:
Abstraction(Implementor* imp) : implementor(imp) {}
void operation() {
implementor->operationImpl();
}
};
Composite Pattern
- Description: Composes objects into tree structures to represent part-whole hierarchies.
- Usage: Handling tree structures.
- Example:
class Component {
public:
virtual void add(Component* c) = 0;
virtual void remove(Component* c) = 0;
virtual void display(int depth) = 0;
};
class Leaf : public Component {
public:
void add(Component* c) override {}
void remove(Component* c) override {}
void display(int depth) override {
std::cout << std::string(depth, '-') << "Leaf" << std::endl;
}
};
class Composite : public Component {
private:
std::vector<Component*> children;
public:
void add(Component* c) override {
children.push_back(c);
}
void remove(Component* c) override {
children.erase(std::remove(children.begin(), children.end(), c), children.end());
}
void display(int depth) override {
std::cout << std::string(depth, '-') << "Composite" << std::endl;
for (auto& child : children) {
child->display(depth + 2);
}
}
};
Decorator Pattern
- Description: Dynamically adds additional responsibilities to an object.
- Usage: Extending functionality.
- Example:
class Component {
public:
virtual void operation() = 0;
};
class ConcreteComponent : public Component {
public:
void operation() override {
std::cout << "ConcreteComponent operation." << std::endl;
}
};
class Decorator : public Component {
protected:
Component* component;
public:
Decorator(Component* c) : component(c) {}
void operation() override {
component->operation();
}
};
class ConcreteDecoratorA : public Decorator {
public:
ConcreteDecoratorA(Component* c) : Decorator(c) {}
void operation() override {
Decorator::operation();
std::cout << "ConcreteDecoratorA added functionality." << std::endl;
}
};
Proxy Pattern
- Description: Provides a surrogate or placeholder for another object to control access to it.
- Usage: Access control, lazy loading, etc.
- Example:
class Subject {
public:
virtual void request() = 0;
};
class RealSubject : public Subject {
public:
void request() override {
std::cout << "RealSubject request." << std::endl;
}
};
class Proxy : public Subject {
private:
RealSubject* realSubject;
public:
void request() override {
if (realSubject == nullptr) {
realSubject = new RealSubject();
}
realSubject->request();
}
};
Facade Pattern
- Description: Provides a unified interface to a set of interfaces in a subsystem.
- Usage: Simplifying interfaces.
- Example:
class Subsystem1 {
public:
void operation1() {
std::cout << "Subsystem1 operation1." << std::endl;
}
};
class Subsystem2 {
public:
void operation2() {
std::cout << "Subsystem2 operation2." << std::endl;
}
};
class Facade {
private:
Subsystem1* subsystem1;
Subsystem2* subsystem2;
public:
Facade(Subsystem1* s1, Subsystem2* s2) : subsystem1(s1), subsystem2(s2) {}
void operation() {
subsystem1->operation1();
subsystem2->operation2();
}
};
Flyweight Pattern
- Description: Uses sharing to support large numbers of fine-grained objects efficiently.
- Usage: Saving memory resources, reducing object count.
- Example:
class Flyweight {
protected:
int intrinsicState;
public:
virtual void operation(int extrinsicState) = 0;
};
class ConcreteFlyweight : public Flyweight {
public:
void operation(int extrinsicState) override {
std::cout << "ConcreteFlyweight: Intrinsic state = " << intrinsicState
<< ", Extrinsic state = " << extrinsicState << std::endl;
}
};
class FlyweightFactory {
private:
std::unordered_map<int, Flyweight*> pool;
public:
Flyweight* getFlyweight(int intrinsicState) {
auto it = pool.find(intrinsicState);
if (it == pool.end()) {
ConcreteFlyweight* flyweight = new ConcreteFlyweight();
flyweight->intrinsicState = intrinsicState;
pool[intrinsicState] = flyweight;
return flyweight;
}
return it->second;
}
};
Command Pattern
- Description: Encapsulates a request as an object, thereby letting you parameterize clients with different requests.
- Usage: Implementing undo operations, transaction processing, etc.
- Example:
class Command {
public:
virtual void execute() = 0;
};
class SimpleCommand : public Command {
private:
std::string payload;
public:
SimpleCommand(const std::string& payload) : payload(payload) {}
void execute() override {
std::cout << "SimpleCommand: " << payload << std::endl;
}
};
class Invoker {
private:
Command* command;
public:
void setCommand(Command* cmd) {
command = cmd;
}
void action() {
command->execute();
}
};
Chain of Responsibility Pattern
- Description: Avoids coupling the sender of a request to multiple request handlers.
- Usage: Handling multi-level approval processes.
- Example:
class Handler {
protected:
Handler* successor;
public:
void setSuccessor(Handler* successor) {
this->successor = successor;
}
virtual void handleRequest(int request) = 0;
};
class ConcreteHandler1 : public Handler {
public:
void handleRequest(int request) override {
if (request >= 0 && request < 10) {
std::cout << "ConcreteHandler1 handled request: " << request << std::endl;
} else if (successor != nullptr) {
successor->handleRequest(request);
}
}
};
class ConcreteHandler2 : public Handler {
public:
void handleRequest(int request) override {
if (request >= 10 && request < 20) {
std::cout << "ConcreteHandler2 handled request: " << request << std::endl;
} else if (successor != nullptr) {
successor->handleRequest(request);
}
}
};
Observer Pattern
- Description: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
- Usage: Event listening, publish-subscribe mechanism.
- Example:
class Subject {
private:
std::vector<Observer*> observers;
public:
void attach(Observer* observer) {
observers.push_back(observer);
}
void detach(Observer* observer) {
observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
}
void notify() {
for (auto& obs : observers) {
obs->update(this);
}
}
};
class Observer {
public:
virtual void update(Subject* subject) = 0;
};
class ConcreteObserver : public Observer {
public:
void update(Subject* subject) override {
std::cout << "ConcreteObserver received update from " << subject << std::endl;
}
};
State Pattern
- Description: Allows an object to alter its behavior when its internal state changes.
- Usage: Implementing state transitions.
- Example:
class State {
public:
virtual void handle(Context* context) = 0;
};
class Context {
private:
State* currentState;
public:
void setState(State* state) {
currentState = state;
}
void request() {
currentState->handle(this);
}
};
class ConcreteStateA : public State {
public:
void handle(Context* context) override {
std::cout << "ConcreteStateA handling request." << std::endl;
context->setState(new ConcreteStateB());
}
};
class ConcreteStateB : public State {
public:
void handle(Context* context) override {
std::cout << "ConcreteStateB handling request." << std::endl;
context->setState(new ConcreteStateA());
}
};
Strategy Pattern
- Description: Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
- Usage: Algorithm selection.
- Example:
class Strategy {
public:
virtual void algorithmInterface() = 0;
};
class ConcreteStrategyA : public Strategy {
public:
void algorithmInterface() override {
std::cout << "ConcreteStrategyA algorithm." << std::endl;
}
};
class Context {
private:
Strategy* strategy;
public:
Context(Strategy* strategy) : strategy(strategy) {}
void contextInterface() {
strategy->algorithmInterface();
}
};
Template Method Pattern
- Description: Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses.
- Usage: Fixing algorithm framework.
- Example:
class Game {
public:
virtual void initialize() = 0;
virtual void startPlay() = 0;
virtual void endPlay() = 0;
void play() {
initialize();
startPlay();
endPlay();
}
};
class Cricket : public Game {
public:
void initialize() override {
std::cout << "Cricket Game Initialized! Start playing." << std::endl;
}
void startPlay() override {
std::cout << "Cricket Game is started. Enjoy the game!" << std::endl;
}
void endPlay() override {
std::cout << "Cricket Game Finished!" << std::endl;
}
};
class Football : public Game {
public:
void initialize() override {
std::cout << "Football Game Initialized! Start playing." << std::endl;
}
void startPlay() override {
std::cout << "Football Game is started. Enjoy the game!" << std::endl;
}
void endPlay() override {
std::cout << "Football Game Finished!" << std::endl;
}
};
Visitor Pattern
- Description: Separates data structure from data operations.
- Usage: Operating on elements in a data structure.
- Example:
class Element {
public:
virtual void accept(Visitor* visitor) = 0;
};
class ConcreteElementA : public Element {
public:
void accept(Visitor* visitor) override {
visitor->visitConcreteElementA(this);
}
};
class ConcreteElementB : public Element {
public:
void accept(Visitor* visitor) override {
visitor->visitConcreteElementB(this);
}
};
class Visitor {
public:
virtual void visitConcreteElementA(ConcreteElementA* element) = 0;
virtual void visitConcreteElementB(ConcreteElementB* element) = 0;
};
class ConcreteVisitor1 : public Visitor {
public:
void visitConcreteElementA(ConcreteElementA* element) override {
std::cout << "ConcreteVisitor1 visiting ConcreteElementA." << std::endl;
}
void visitConcreteElementB(ConcreteElementB* element) override {
std::cout << "ConcreteVisitor1 visiting ConcreteElementB." << std::endl;
}
};
Iterator Pattern
- Description: Provides a way to sequentially access the elements of an aggregate object without exposing its internal representation.
- Usage: Traversing collections.
- Example:
class Iterator {
public:
virtual bool hasNext() = 0;
virtual std::string next() = 0;
};
class Aggregate {
public:
virtual Iterator* createIterator() = 0;
};
class ConcreteAggregate : public Aggregate {
private:
std::vector<std::string> items;
public:
void addItem(const std::string& item) {
items.push_back(item);
}
Iterator* createIterator() override {
return new ConcreteIterator(items.begin(), items.end());
}
};
class ConcreteIterator : public Iterator {
private:
std::vector<std::string>::iterator current;
std::vector<std::string>::iterator end;
public:
ConcreteIterator(std::vector<std::string>::iterator begin, std::vector<std::string>::iterator end)
: current(begin), end(end) {}
bool hasNext() override {
return current != end;
}
std::string next() override {
if (hasNext()) {
std::string item = *current;
++current;
return item;
}
return "";
}
};
Example Usage
int main() {
// Create ConcreteAggregate object
ConcreteAggregate aggregate;
aggregate.addItem("Item 1");
aggregate.addItem("Item 2");
aggregate.addItem("Item 3");
// Get iterator
Iterator* iterator = aggregate.createIterator();
// Traverse collection
while (iterator->hasNext()) {
std::string item = iterator->next();
std::cout << "Current Item: " << item << std::endl;
}
delete iterator; // Release iterator resources
return 0;
}
Architecture Design
Basic Concepts and Principles
SOLID Principles
- Single Responsibility Principle (SRP): A class should have only one reason to change.
- Open-Closed Principle (OCP): Software entities should be open for extension but closed for modification.
- Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types.
- Interface Segregation Principle (ISP): Clients should not be forced to depend on methods they do not use.
- Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules; both should depend on abstractions.
Architecture Patterns
MVC (Model-View-Controller)
- Model: Handles data logic.
- View: Responsible for displaying data.
- Controller: Handles input and controls model and view.
- MVVM (Model-View-ViewModel)
- Model: Handles data logic.
- View: Responsible for displaying data.
- ViewModel: Handles data binding and logic processing.
Modularization and Componentization
Modularization
- Decomposes the system into independent functional modules, each responsible for specific functionality.
- Example: Database module, network communication module, UI module, etc.
Componentization
- Further refines modules into reusable components.
- Example: Database access component, network request component, etc.
Dependency Management
Dependency Injection
Inject dependencies via constructor, setter, or interface.
Example:
class Database {
public:
void connect() {}
};
class Service {
Database* db;
public:
Service(Database* db) : db(db) {}
void performAction() {
db->connect();
}
};
Dependency Inversion High-level modules should not depend on low-level modules; both should depend on abstractions.
Example:
class DatabaseInterface {
public:
virtual void connect() = 0;
};
class ConcreteDatabase : public DatabaseInterface {
public:
void connect() override {}
};
class Service {
DatabaseInterface* db;
public:
Service(DatabaseInterface* db) : db(db) {}
void performAction() {
db->connect();
}
};Test-Driven Development (TDD)
Unit Testing
- Write tests for small functional units.
- Example:
#include <gtest/gtest.h>
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};
TEST(CalculatorTest, Add) {
Calculator calc;
EXPECT_EQ(calc.add(1, 2), 3);
}
Integration Testing
- Test interactions between different modules.
- Example:
TEST(IntegrationTest, DatabaseService) {
Database db;
Service service(&db);
service.performAction();
// Check database connection status, etc.
}
Performance Optimization
Memory Management
- Manually manage memory to avoid leaks.
- Example:
class MyClass {
public:
MyClass() {
data = new int[100];
}
~MyClass() {
delete[] data;
}
private:
int* data;
};
Multithreaded Programming
- Leverage modern CPU multi-core advantages.
- Example:
#include <thread>
#include <mutex>
std::mutex mtx;
void threadFunction() {
std::lock_guard<std::mutex> lock(mtx);
// Perform task
}
int main() {
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t1.join();
t2.join();
return 0;
}
Security Considerations
Input Validation
- Ensure all external inputs are safe and reliable.
- Example:
bool isValidInput(const std::string& input) {
// Validate if input is legal
return true;
}
Error Handling
- Gracefully handle runtime errors.
- Example:
try {
// Code that may throw exceptions
} catch (const std::exception& e) {
// Handle exception
}
Practical Case Analysis
Step-by-Step Analysis Using the Singleton pattern as an example:
class Singleton {
private:
static Singleton* instance;
Singleton() {} // Private constructor
public:
static Singleton* getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
~Singleton() { delete instance; }
};
Singleton* Singleton::instance = nullptr;
int main() {
Singleton* s = Singleton::getInstance();
return 0;
}
Code Analysis:
- Uses a static member variable to store the unique instance.
- Privatizes the constructor to prevent external instantiation.
- The getInstance method ensures the singleton pattern is correctly implemented.
Tools and Frameworks
CMake Build Tool Example:
cmake_minimum_required(VERSION 3.10)
project(MyProject)
add_executable(myapp main.cpp)
Boost A library collection providing extensive functionality support.
#include <boost/algorithm/string.hpp>
std::string str = "hello world";
boost::to_upper(str);
Qt A cross-platform application framework. Example:
#include <QApplication>
#include <QLabel>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QLabel label("Hello, Qt!");
label.show();
return app.exec();
}
Best Practices
Code Review
- Conduct regularly to improve code quality.
- Example:
- Use tools like clang-tidy for static analysis.
- Conduct regular internal team code reviews.
Continuous Integration/Continuous Deployment (CI/CD)
- Automate testing and deployment processes.
- Example:
- Use Jenkins or GitLab CI for automated building and deployment.
Advanced Topics
Domain-Driven Design (DDD)
- A software development approach focused on complex business logic.
- Example:
- Define domain models, aggregate roots, etc.
Microservices Architecture
- Develop a single application as a suite of small services.
- Example:
- Use RESTful API or gRPC for inter-service communication.



