r3plica
r3plica

Reputation: 13367

Factory design pattern woes

So I have this factory class which I believe is exactly as a static factory class should be:

public class FileFactory
{
    public static File Create(IObjectService service, string destination, string fileName, string mimeType)
    {
        var type = mimeType.ToLower().Split('/')[0];

        switch(type)
        {
            case "image":
                return new Image(service, destination, fileName);
            case "document":
                return new Document(service, destination, fileName);
            default:
                return new Document(service, destination, fileName);
        }
    }
}

Now, I have another class which is not static and is a whole lot more complicated:

public class MetadataFactory
{
    public string destination;
    public string fileName;
    public string fullPath;

    private XDocument document;

    private XNamespace SystemNamespace = "http://ns.exiftool.ca/File/System/1.0/";
    private XNamespace FileNamespace = "http://ns.exiftool.ca/File/1.0/";
    private XNamespace Composite = "http://ns.exiftool.ca/Composite/1.0/";
    private XNamespace PNG = "http://ns.exiftool.ca/PNG/PNG/1.0/";
    private XNamespace GIF = "http://ns.exiftool.ca/GIF/GIF/1.0/";
    private XNamespace IFD0 = "http://ns.exiftool.ca/EXIF/IFD0/1.0/";
    private XNamespace IFD1 = "http://ns.exiftool.ca/EXIF/IFD1/1.0/";
    private XNamespace BMP = "http://ns.exiftool.ca/BMP/BMP/1.0/";
    private XNamespace JFIF = "http://ns.exiftool.ca/JFIF/JFIF/1.0/";
    private XNamespace XMPtiff = "http://ns.exiftool.ca/XMP/XMP-tiff/1.0/";
    private XNamespace XMPxmp = "http://ns.exiftool.ca/XMP/XMP-xmp/1.0/";
    private XNamespace PDF = "http://ns.exiftool.ca/PDF/PDF/1.0/";
    private XNamespace FlashPix = "http://ns.exiftool.ca/FlashPix/FlashPix/1.0/";
    private XNamespace XML = "http://ns.exiftool.ca/XML/XML/1.0/";

    public Metadata Create(string destination, string fileName, string exifToolPath)
    {
        this.destination = destination;
        this.fileName = fileName;
        this.fullPath = Path.Combine(destination, fileName);
        this.document = new XDocument(GetFullXml(exifToolPath));

        var mime = (string)this.document.Descendants(FileNamespace + "MIMEType").FirstOrDefault();
        var type = mime.ToLower().Split('/')[0];

        var metadata = new Metadata()
        {
            ReferenceId = this.GenerateId(),

            FileSize = (string)this.document.Descendants(SystemNamespace + "FileSize").FirstOrDefault(),
            FileType = (string)this.document.Descendants(FileNamespace + "FileType").FirstOrDefault(),
            MIMEType = (string)this.document.Descendants(FileNamespace + "MIMEType").FirstOrDefault(),
        };

        switch (type)
        {
            case "image":

                metadata.CreateDate = this.GetCreateDate();
                metadata.ModifyDate = this.GetModifyDate();

                metadata.ImageWidth = this.GetImageWidth();
                metadata.ImageHeight = this.GetImageHeight();
                metadata.ImageSize = this.GetImageSize();

                metadata.Orientation = (string)this.document.Descendants(XMPtiff + "Orientation").FirstOrDefault();

                break;

            case "document":

                metadata.CreateDate = this.GetCreateDate();
                metadata.ModifyDate = this.GetModifyDate();

                break;
        }

        return metadata;
    }        

    private XElement GetFullXml(string exifToolPath)
    {
        string args = string.Format("-X \"{0}\"", this.fullPath);
        string output = RunProcess(exifToolPath, args);
        output = Sanitize(output);

        return new XElement("FullMetadata", XElement.Parse(output));
    }

    private virtual string GetCreateDate()
    {
        if (this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(PDF + "CreateDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(PDF + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(FlashPix + "CreateDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(FlashPix + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(XML + "CreateDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(XML + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(Composite + "DateTimeCreated").FirstOrDefault() != null)
            return (string)this.document.Descendants(Composite + "DateTimeCreated").FirstOrDefault();

        return null;
    }

    private virtual string GetModifyDate()
    {
        if (this.document.Descendants(IFD0 + "ModifyDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(IFD0 + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(PDF + "ModifyDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(PDF + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(FlashPix + "ModifyDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(FlashPix + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(XML + "ModifyDate").FirstOrDefault() != null)
            return (string)this.document.Descendants(XML + "ModifyDate").FirstOrDefault();

        return null;
    }

    private virtual string GetDuration()
    {
        if (this.document.Descendants(Composite + "Duration").FirstOrDefault() != null)
            return (string)this.document.Descendants(Composite + "Duration").FirstOrDefault();

        return null;
    }

    private virtual int GetImageWidth()
    {
        if (this.document.Descendants(PNG + "ImageWidth").FirstOrDefault() != null)
            return (int)this.document.Descendants(PNG + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(GIF + "ImageWidth").FirstOrDefault() != null)
            return (int)this.document.Descendants(GIF + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(IFD0 + "ImageWidth").FirstOrDefault() != null)
            return (int)this.document.Descendants(IFD0 + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(BMP + "ImageWidth").FirstOrDefault() != null)
            return (int)this.document.Descendants(BMP + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(FileNamespace + "ImageWidth").FirstOrDefault() != null)
            return (int)this.document.Descendants(FileNamespace + "ImageWidth").FirstOrDefault();

        return 0;
    }

    private virtual int GetImageHeight()
    {
        if (this.document.Descendants(PNG + "ImageHeight").FirstOrDefault() != null)
            return (int)this.document.Descendants(PNG + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(GIF + "ImageHeight").FirstOrDefault() != null)
            return (int)this.document.Descendants(GIF + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(IFD0 + "ImageHeight").FirstOrDefault() != null)
            return (int)this.document.Descendants(IFD0 + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(BMP + "ImageHeight").FirstOrDefault() != null)
            return (int)this.document.Descendants(BMP + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(FileNamespace + "ImageHeight").FirstOrDefault() != null)
            return (int)this.document.Descendants(FileNamespace + "ImageHeight").FirstOrDefault();

        return 0;
    }

    private virtual string GetImageSize()
    {
        if (this.document.Descendants(PNG + "ImageSize").FirstOrDefault() != null)
            return (string)this.document.Descendants(PNG + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(GIF + "ImageSize").FirstOrDefault() != null)
            return (string)this.document.Descendants(GIF + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(IFD0 + "ImageSize").FirstOrDefault() != null)
            return (string)this.document.Descendants(IFD0 + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(BMP + "ImageSize").FirstOrDefault() != null)
            return (string)this.document.Descendants(BMP + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(Composite + "ImageSize").FirstOrDefault() != null)
            return (string)this.document.Descendants(Composite + "ImageSize").FirstOrDefault();

        return null;
    }

    private string GenerateId()
    {
        long i = 1;
        foreach (byte b in Guid.NewGuid().ToByteArray())
        {
            i *= ((int)b + 1);
        }
        return string.Format("{0:x}", i - DateTime.Now.Ticks);
    }

    private string RunProcess(string exifToolPath, string args)
    {
        if (String.IsNullOrEmpty(exifToolPath))
            throw new SystemException("EXIFTool Executable Path Not Configured");

        if (!System.IO.File.Exists(exifToolPath))
            throw new SystemException("EXIFTool Executable Not Found: " + exifToolPath);

        var process = new Process
        {
            StartInfo =
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                FileName = exifToolPath,
                Arguments = args
            }
        };

        process.Start();

        var output = process.StandardOutput.ReadToEnd();
        process.WaitForExit();

        return output;
    }

    private string Sanitize(string s)
    {
        return s.Replace("&", string.Empty);
    }
}

I call these two factories like so:

var metadata = new MetadataFactory().Create(this.uploadPath, asset.FileName, this.exifToolPath);
var file = FileFactory.Create(objectService, this.uploadPath, asset.FileName, metadata.MIMEType);

Now, the problem is this. The FileFactory returns either a Document or Image which inherit from File. To me, this is the correct way of building a factory.

MetadataFactory on the other hand only returns Metadata and it can only get the metadata by extracting it from the file using Exif. So, my question is: Is the factory the correct pattern to use for this or should I consider doing something else?

Just to clarify a couple of things.

Metadata is a POCO class Metadata can only be built by running a process which extracts xml data using Exif

Please help me if you can :)

Upvotes: 1

Views: 211

Answers (2)

r3plica
r3plica

Reputation: 13367

So, I took the Builder Design Pattern (suggested by Ondrej) and applied it to my metadata. This is how it went.

First I created my IMetadataBuilder interface:

interface IMetadataBuilder
{
    void SetCreateDate();
    void SetModifyDate();
    void SetImageWidth();
    void SetImageHeight();
    void SetImageSize();
    Metadata GetMetadata();
}

pretty straight forward, then from there I created my DocumentMetadataBuilder and ImageMetadataBuilder like this:

public class DocumentMetadataBuilder : IMetadataBuilder
{
    private readonly Metadata metadata;
    private readonly XDocument document;

    private XNamespace Composite = "http://ns.exiftool.ca/Composite/1.0/";
    private XNamespace XMPxmp = "http://ns.exiftool.ca/XMP/XMP-xmp/1.0/";
    private XNamespace PDF = "http://ns.exiftool.ca/PDF/PDF/1.0/";
    private XNamespace FlashPix = "http://ns.exiftool.ca/FlashPix/FlashPix/1.0/";
    private XNamespace XML = "http://ns.exiftool.ca/XML/XML/1.0/";

    public DocumentMetadataBuilder(XDocument document, string fileSize, string fileType, string mimeType)
    {
        this.document = document;
        this.metadata = new Metadata()
        {
            FileSize = fileSize,
            FileType = fileType,
            MIMEType = mimeType
        };
    }

    public void SetCreateDate()
    {
        var createDate = string.Empty;

        if (this.document.Descendants(PDF + "CreateDate").FirstOrDefault() != null)
            createDate = (string)this.document.Descendants(PDF + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault() != null)
            createDate = (string)this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(FlashPix + "CreateDate").FirstOrDefault() != null)
            createDate = (string)this.document.Descendants(FlashPix + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(XML + "CreateDate").FirstOrDefault() != null)
            createDate = (string)this.document.Descendants(XML + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(Composite + "DateTimeCreated").FirstOrDefault() != null)
            createDate = (string)this.document.Descendants(Composite + "DateTimeCreated").FirstOrDefault();

        this.metadata.CreateDate = createDate;
    }

    public void SetModifyDate()
    {
        var modifyDate = string.Empty;

        if (this.document.Descendants(PDF + "ModifyDate").FirstOrDefault() != null)
            modifyDate = (string)this.document.Descendants(PDF + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault() != null)
            modifyDate = (string)this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(FlashPix + "ModifyDate").FirstOrDefault() != null)
            modifyDate = (string)this.document.Descendants(FlashPix + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(XML + "ModifyDate").FirstOrDefault() != null)
            modifyDate = (string)this.document.Descendants(XML + "ModifyDate").FirstOrDefault();

        this.metadata.ModifyDate = modifyDate;
    }

    public void SetImageWidth()
    {
        throw new NotImplementedException();
    }

    public void SetImageHeight()
    {
        throw new NotImplementedException();
    }

    public void SetImageSize()
    {
        throw new NotImplementedException();
    }

    public Metadata GetMetadata()
    {
        throw new NotImplementedException();
    }
}

and

public class ImageMetadataBuilder : IMetadataBuilder
{
    private readonly Metadata metadata;
    private readonly XDocument document;

    private XNamespace SystemNamespace = "http://ns.exiftool.ca/File/System/1.0/";
    private XNamespace FileNamespace = "http://ns.exiftool.ca/File/1.0/";
    private XNamespace Composite = "http://ns.exiftool.ca/Composite/1.0/";
    private XNamespace PNG = "http://ns.exiftool.ca/PNG/PNG/1.0/";
    private XNamespace GIF = "http://ns.exiftool.ca/GIF/GIF/1.0/";
    private XNamespace IFD0 = "http://ns.exiftool.ca/EXIF/IFD0/1.0/";
    private XNamespace IFD1 = "http://ns.exiftool.ca/EXIF/IFD1/1.0/";
    private XNamespace BMP = "http://ns.exiftool.ca/BMP/BMP/1.0/";
    private XNamespace JFIF = "http://ns.exiftool.ca/JFIF/JFIF/1.0/";
    private XNamespace XMPtiff = "http://ns.exiftool.ca/XMP/XMP-tiff/1.0/";
    private XNamespace XMPxmp = "http://ns.exiftool.ca/XMP/XMP-xmp/1.0/";
    private XNamespace PDF = "http://ns.exiftool.ca/PDF/PDF/1.0/";
    private XNamespace FlashPix = "http://ns.exiftool.ca/FlashPix/FlashPix/1.0/";
    private XNamespace XML = "http://ns.exiftool.ca/XML/XML/1.0/";

    public ImageMetadataBuilder(XDocument document, string fileSize, string fileType, string mimeType)
    {
        this.document = document;
        this.metadata = new Metadata()  {
            FileSize = fileSize,
            FileType = fileType,
            MIMEType = mimeType
        };
    }

    public void SetCreateDate()
    {
        var createDate = string.Empty;

        if (this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault() != null)
            createDate = (string)this.document.Descendants(XMPxmp + "CreateDate").FirstOrDefault();

        if (this.document.Descendants(Composite + "DateTimeCreated").FirstOrDefault() != null)
            createDate = (string)this.document.Descendants(Composite + "DateTimeCreated").FirstOrDefault();

        this.metadata.CreateDate = createDate;
    }

    public void SetModifyDate()
    {
        var modifyDate = string.Empty;

        if (this.document.Descendants(IFD0 + "ModifyDate").FirstOrDefault() != null)
            modifyDate = (string)this.document.Descendants(IFD0 + "ModifyDate").FirstOrDefault();

        if (this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault() != null)
            modifyDate = (string)this.document.Descendants(XMPxmp + "ModifyDate").FirstOrDefault();

        this.metadata.ModifyDate = modifyDate;
    }

    public void SetImageWidth()
    {
        var imageWidth = 0;

        if (this.document.Descendants(PNG + "ImageWidth").FirstOrDefault() != null)
            imageWidth = (int)this.document.Descendants(PNG + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(GIF + "ImageWidth").FirstOrDefault() != null)
            imageWidth = (int)this.document.Descendants(GIF + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(IFD0 + "ImageWidth").FirstOrDefault() != null)
            imageWidth = (int)this.document.Descendants(IFD0 + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(BMP + "ImageWidth").FirstOrDefault() != null)
            imageWidth = (int)this.document.Descendants(BMP + "ImageWidth").FirstOrDefault();

        if (this.document.Descendants(FileNamespace + "ImageWidth").FirstOrDefault() != null)
            imageWidth = (int)this.document.Descendants(FileNamespace + "ImageWidth").FirstOrDefault();

        this.metadata.ImageWidth = imageWidth;
    }

    public void SetImageHeight()
    {
        var imageHeight = 0;

        if (this.document.Descendants(PNG + "ImageHeight").FirstOrDefault() != null)
            imageHeight = (int)this.document.Descendants(PNG + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(GIF + "ImageHeight").FirstOrDefault() != null)
            imageHeight = (int)this.document.Descendants(GIF + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(IFD0 + "ImageHeight").FirstOrDefault() != null)
            imageHeight = (int)this.document.Descendants(IFD0 + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(BMP + "ImageHeight").FirstOrDefault() != null)
            imageHeight = (int)this.document.Descendants(BMP + "ImageHeight").FirstOrDefault();

        if (this.document.Descendants(FileNamespace + "ImageHeight").FirstOrDefault() != null)
            imageHeight = (int)this.document.Descendants(FileNamespace + "ImageHeight").FirstOrDefault();

        this.metadata.ImageHeight = imageHeight;
    }

    public void SetImageSize()
    {
        var imageSize = string.Empty;

        if (this.document.Descendants(PNG + "ImageSize").FirstOrDefault() != null)
            imageSize = (string)this.document.Descendants(PNG + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(GIF + "ImageSize").FirstOrDefault() != null)
            imageSize = (string)this.document.Descendants(GIF + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(IFD0 + "ImageSize").FirstOrDefault() != null)
            imageSize = (string)this.document.Descendants(IFD0 + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(BMP + "ImageSize").FirstOrDefault() != null)
            imageSize = (string)this.document.Descendants(BMP + "ImageSize").FirstOrDefault();

        if (this.document.Descendants(Composite + "ImageSize").FirstOrDefault() != null)
            imageSize = (string)this.document.Descendants(Composite + "ImageSize").FirstOrDefault();

        this.metadata.ImageSize = imageSize;
    }

    public Metadata GetMetadata()
    {
        return metadata;
    }
}

I think the first thing to notice is the constructor for both these classes. I pass in an XDocument (which is the metadata in xml format, but I also pass in the fileSize, fileType and MimeType which I use to create an instance of my Metadata.

In the DocumentMetadataBuilder class, even though I implement IMetadataBuilder most of the methods actually throw a NotImplementedException. This is done on purpose and become evident in my Director class:

public class MetadataCreator
{
    private XNamespace FileNamespace = "http://ns.exiftool.ca/File/1.0/";
    private XNamespace SystemNamespace = "http://ns.exiftool.ca/File/System/1.0/";

    private IMetadataBuilder builder;

    public Metadata Create(string destination, string fileName, string exifToolPath)
    {
        var fullPath = Path.Combine(destination, fileName);
        var document = new XDocument(GetFullXml(fullPath, exifToolPath));

        var fileSize = (string)document.Descendants(SystemNamespace + "FileSize").FirstOrDefault();
        var fileType = (string)document.Descendants(FileNamespace + "FileType").FirstOrDefault();
        var mimeType = (string)document.Descendants(FileNamespace + "MIMEType").FirstOrDefault();
        var type = mimeType.ToLower().Split('/')[0];

        switch (type)
        {
            case "image":

                builder = new ImageMetadataBuilder(document, fileSize, fileType, mimeType);
                builder.SetCreateDate();
                builder.SetModifyDate();
                builder.SetImageWidth();
                builder.SetImageHeight();
                builder.SetImageSize();

                break;

            case "document":

                builder = new DocumentMetadataBuilder(document, fileSize, fileType, mimeType);
                builder.SetCreateDate();
                builder.SetModifyDate();

                break;
        }

        return builder.GetMetadata();
    }

    private XElement GetFullXml(string filePath, string exifToolPath)
    {
        string args = string.Format("-X \"{0}\"", filePath);
        string output = RunProcess(exifToolPath, args);
        output = Sanitize(output);

        return new XElement("FullMetadata", XElement.Parse(output));
    }
    private string GenerateId()
    {
        long i = 1;
        foreach (byte b in Guid.NewGuid().ToByteArray())
        {
            i *= ((int)b + 1);
        }
        return string.Format("{0:x}", i - DateTime.Now.Ticks);
    }

    private string RunProcess(string exifToolPath, string args)
    {
        if (String.IsNullOrEmpty(exifToolPath))
            throw new SystemException("EXIFTool Executable Path Not Configured");

        if (!System.IO.File.Exists(exifToolPath))
            throw new SystemException("EXIFTool Executable Not Found: " + exifToolPath);

        var process = new Process
        {
            StartInfo =
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                FileName = exifToolPath,
                Arguments = args
            }
        };

        process.Start();

        var output = process.StandardOutput.ReadToEnd();
        process.WaitForExit();

        return output;
    }

    private string Sanitize(string s)
    {
        return s.Replace("&", string.Empty);
    }
}

Now, with the Director class I have decided to combine both Get and Create into one method because I did not want to call the Create method and then call the Get method everytime. I could see no reason not to return the Metadata class when calling Create.

The other thing to notice is that I call different methods based on the IMetadataBuilder concrete class. The ImageMetadataBuilder calls all the public methods and the DocumentMetadataBuilder only calls SetCreateDate and SetModifyDate.

Then you can see I return the IMetadataBuilder *GetMetadata* method.

This is called like this:

var metadata = (asset.Metadata == null) ? new MetadataCreator().Create(this.uploadPath, asset.FileName, this.exifToolPath) : asset.Metadata;

Unless I have totally missed the boat, I believe this is a good example of the Builder Design Pattern

Upvotes: 0

Ondrej Janacek
Ondrej Janacek

Reputation: 12616

So I have this factory class which I believe is exactly as a static factory class should be

There's no such a pattern. There are only "Factory method" and "Abstract factory". You might have a class with a static factory method, but not static factory class.

The second class is conceptually more like a Builder than a Factory method. Factories should be short methods with a single purpose - returning an object based on agruments provided. A builder is more suited for a construction of complex objects.

Upvotes: 3

Related Questions