I have a class Container, which represents wrapper around std::list. This class contains following public methods:

  • void add(Shape *item)
  • void next()
  • void setBegin()
  • Shape* curr()

and protected variables

  • std::list <Shape*> _container
  • std::list <Shape*>::iterator _iter

Now I need add sorting of Container without changing existing class code.

Which pattern should I use? I think, that Decorator is most appropriate pattern in this case. Should I redesign class Container?

3 Answers 3


Container as it stands is both a list and an iterator, so I would actually suggest breaking it into two classes - one for each of the responsibilities. You can then make an alternative implementation of the list container that is sortable.


class UnorderedContainer : Container

class SortableContainer : Container
    void Sort();

abstract class Container
    void Add(Shape *item);
    Iterator GetIterator();

class Iterator
    Shape* Current();
    void Next();

I'd also carefully consider whether the list is mutable while you are using next() to iterate through it. It's not at all obvious what would happens when you call next() after a sort() - can it revisit items that you have already stepped through? If you break out the iterator into its own class you could have it act on an immutable copy of the list taken at the point where you began the iteration.

  • Each subclass must be contain std::list object? Commented Nov 28, 2013 at 10:01
  • You'd only really std::list in the base class, unless the list is likely to be big enough that the implementation might need to change for your sorting algorithm to be performant.
    – Mr Cochese
    Commented Nov 29, 2013 at 8:51

Yes, Decorator is exactly what you are seeking. Actually, you Container class is already a decorator for std::list.


You can create a sub class of Container class eg SortedContainer and add sorted functionality in the derived class. It will satisfies both principles, mentioned below.

  • Open Close Principle
  • Liskov Substituion Principle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.