Mastering Design Patterns with Examples — Iterator and Composite Patterns

Keep your collections well encapsulated

Larry | Peng Yang
Computer Science Fundamentals

--

Photo by Tim Johnson on Unsplash

Overview

In this chapter, we are going to walk you through two design patterns: Iterator and composite with which you’re going to see how you can allow your clients to iterate through your objects without ever getting a peek at how you store your objects. You’re also going to learn how to create some super collections of objects that can leap over some impressive data structures in a single bound. And if that’s not enough, you’re also going to learn a thing or two about object responsibility.

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. This pattern promotes loose coupling and makes your code cleaner and easier to understand.

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Essentially, it lets you treat individual objects and compositions of objects uniformly.

Use Iterator Pattern in Diner and Pancake House Merge

Understanding the problem

--

--