lundi 23 avril 2018

What are the names of these design patterns and their use cases?

Suppose the following simple Object class:

class Object
{
public:
    Object();

    // Sets the name of this object
    void setName(const std::string &name);

private:
    Uuid id;
    std::string name;
}

We can encapsulate it using the following design patterns:

Design Pattern 1

class ObjectManager
{
public:
    ObjectManager();

    // Creates and stores an object, returning an unique id
    Uuid createObject();

    // Sets the name of object specified by id to name
    void setObjectName(Uuid id, const std::string &name);

private:
    std::vector<Object> objects_;
}

This pattern completely encapsulates the concept of Object. It provides calling code with identifier handles that can be used with an interface to manipulate the created objects.

Design Pattern 1 - Usage

 Uuid id = manager.createObject();
 manager.setName(id, "Hello World");

Design Pattern 2

class ObjectManager
{
public:
    ObjectManager();

    // Adds object to this manager (creates copy for example, could use shared_ptr)
    void addObject(const Object &object);

private:
    std::vector<Object> objects_;
}

This pattern puts the onus on calling code to create the object, modify it and then add it to the manager.

Design Pattern 2 - Usage

 Object object;
 object.setName("Hello World");

 manager.addObject(object);

Questions

  1. What are the names of these two design patterns?
  2. What are the pros and cons of each pattern?
  3. When should a programmer prefer one over the other?

Note: Please excuse the ambiguous title, I will update it once I have more information on the patterns to better represent the question.

Aucun commentaire:

Enregistrer un commentaire