Algo-Sim › Design Patterns

Composite: folder sizes

Easy · Design Patterns · step through it in Java, Python and C++ on your own input

Treat single objects and groups the same way: files and folders share one Entry interface, and a folder answers size() by asking each child, whatever it is.

Problem

Build a file system where node 0 is the root folder. folder(parent) and file(parent, bytes) add a node under a folder and return its new id (1, 2, …). size(id) returns the bytes under that node: a file’s own size, or the sum over everything inside a folder. Files and folders must share one interface, so callers never check which one they hold.

Constraints

Edge cases to test

Follow-up questions

Where do child-management methods go?
Only on the composite (safer), or on the shared interface (uniform but leaves throw); choose and say why.
How do you avoid recomputing sizes?
Cache each folder’s size and invalidate it up the parent chain when a child changes.

Solution

Java

interface Entry {                       // files and folders look the same
    int size();
}

class FileNode implements Entry {
    private final int bytes;
    FileNode(int bytes) { this.bytes = bytes; }
    public int size() { return bytes; }
}

class Folder implements Entry {
    final List<Entry> children = new ArrayList<>();

    public int size() {
        int total = 0;
        for (Entry child : children)
            total += child.size();
        return total;
    }
}

class FileSystem {
    private final List<Entry> nodes = new ArrayList<>();

    FileSystem() {
        nodes.add(new Folder());                // node 0 is the root
    }

    public int folder(int parent) { return add(parent, new Folder()); }
    public int file(int parent, int bytes) { return add(parent, new FileNode(bytes)); }

    private int add(int parent, Entry node) {
        ((Folder) nodes.get(parent)).children.add(node);
        nodes.add(node);
        return nodes.size() - 1;
    }

    public int size(int id) {
        return nodes.get(id).size();
    }
}

Python

class FileNode:                         # files and folders look the same
    def __init__(self, size_bytes):
        self.size_bytes = size_bytes

    def size(self):
        return self.size_bytes


class Folder:
    def __init__(self):
        self.children = []

    def size(self):
        total = 0
        for child in self.children:
            total += child.size()
        return total


class FileSystem:
    def __init__(self):
        self.nodes = [Folder()]                 # node 0 is the root

    def folder(self, parent):
        return self._add(parent, Folder())

    def file(self, parent, size_bytes):
        return self._add(parent, FileNode(size_bytes))

    def _add(self, parent, node):
        self.nodes[parent].children.append(node)
        self.nodes.append(node)
        return len(self.nodes) - 1

    def size(self, node_id):
        return self.nodes[node_id].size()

C++

#include <bits/stdc++.h>
using namespace std;
struct Entry {
    virtual int size() const = 0;
    virtual ~Entry() = default;
};
class FileNode : public Entry {
    int bytes;

  public:
    explicit FileNode(int b)
        : bytes(b) {}
    int size() const override {
        return bytes;
    }
};
struct Folder : Entry {
    vector<shared_ptr<Entry>> children;
    int size() const override {
        int total = 0;
        for (const auto &child : children)
            total += child->size();
        return total;
    }
};
class FileSystem {
    vector<shared_ptr<Entry>> nodes{make_shared<Folder>()};
    int add(int parent, shared_ptr<Entry> node) {
        dynamic_pointer_cast<Folder>(nodes[parent])->children.push_back(node);
        nodes.push_back(move(node));
        return int(nodes.size()) - 1;
    }

  public:
    int folder(int parent) {
        return add(parent, make_shared<Folder>());
    }
    int file(int parent, int bytes) {
        return add(parent, make_shared<FileNode>(bytes));
    }
    int size(int id) {
        return nodes[id]->size();
    }
};

More Design Patterns problems