title: How can I use the builder pattern to construct various similar object types?
body: <p>I am currently using the builder pattern as defined here:</p>
  
  <p><a href="https://stackoverflow.com/questions/7302891/the-builder-pattern-and-a-large-number-of-mandatory-parameters">Previous question showing my use of the builder pattern</a></p>
  
  <p>The problem I've now encountered is a requirement to create the following structure:</p>
  
  <pre><code>- ZipHolder: file metadata present
      * File mainFile
      * File optionalFile
      * List&lt;File&gt; files
  </code></pre>
  
  <p>OR:</p>
  
  <pre><code>- ZipHolder: no file metadata present
      * File mainFile
      * File optionalFile
      * List&lt;File&gt; files
  </code></pre>
  
  <p>Both <code>ZipHolder</code> and <code>File</code> are constructed using the builder pattern, implemented as an internal static class of each. A <code>ZipHolder</code> takes a <code>mainFile</code> as a mandatory constructor parameter and prefills some information in the <code>ZipHolder</code>, which can be overridden, should the need arise. A <code>File</code> contains file content and associated metadata pertaining to that file. Validation on both the <code>ZipHolder</code> and <code>File</code> is then performed when calling the <code>build()</code> method of each's <code>Builder</code> class. The objects are then taken and output to a ZIP file hierarchy that should then be read in to the same object structure, if required.</p>
  
  <p>This works nicely and gives a degree of flexibility in object creation while ensuring immutability. I have encountered a problem though. A new requirement has presented itself, mandating that <code>File</code> objects can either have metadata <strong>and</strong> file content <em>OR</em> <strong>only</strong> file content. I figured I could simply pass a boolean flag value to the builder for the <code>ZipHolder</code> object to allow the skipping of the usual metadata validation. This would seem ok but then it requires a <code>File</code> <em>mainFile</em> to be constructed - essentially, a chicken and egg situation. My next thought was to move the flag to the <code>File</code> class. This seemed ok until I realised that you could potentially create multiple <code>File</code> objects, some with metadata required and others with only the file content, with no means of enforcing constraints across the board.</p>
  
  <p>So I am somewhat stumped as to how to proceed. I can't see an obvious means of decoupling the requirement of a <em>mainFile</em> for a <code>ZipHolder</code> in an elegant fashion. Concepts like abstract classes, interfaces, base classes and things like that come to mind but I'm in need of some direction in this particular situation.</p>
  
  <p>So my question is:</p>
  
  <p>Can I allow for both scenarios while retaining the builder pattern per the reasons in my link above?</p>