How does a factory know which type of object to create?

前端 未结 5 1713
旧时难觅i
旧时难觅i 2021-02-05 12:04

I believe the factory method design pattern is appropriate for what I\'m trying to do, but I\'m not sure how much responsibility (knowledge of subclasses it creates) to give it.

5条回答
  •  盖世英雄少女心
    2021-02-05 12:31

    If this is for windows I would try to guess content type and then use factory. In fact I did this some time ago.

    Here is a class to guess content type of a file:

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    
    namespace Nexum.Abor.Common
    {
        /// 
        /// This will work only on windows
        /// 
        public class MimeTypeFinder
        {
            [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
            private extern static UInt32 FindMimeFromData(
                UInt32 pBC,
                [MarshalAs(UnmanagedType.LPStr)] String pwzUrl,
                [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
                UInt32 cbSize,
                [MarshalAs(UnmanagedType.LPStr)]String pwzMimeProposed,
                UInt32 dwMimeFlags,
                out UInt32 ppwzMimeOut,
                UInt32 dwReserverd
            );
    
            public string getMimeFromFile(string filename)
            {
                if (!File.Exists(filename))
                    throw new FileNotFoundException(filename + " not found");
    
                var buffer = new byte[256];
                using (var fs = new FileStream(filename, FileMode.Open))
                {
                    if (fs.Length >= 256)
                        fs.Read(buffer, 0, 256);
                    else
                        fs.Read(buffer, 0, (int)fs.Length);
                }
                try
                {
                    UInt32 mimetype;
                    FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
                    var mimeTypePtr = new IntPtr(mimetype);
                    var mime = Marshal.PtrToStringUni(mimeTypePtr);
                    Marshal.FreeCoTaskMem(mimeTypePtr);
                    return mime;
                }
                catch (Exception)
                {
                    return "unknown/unknown";
                }
            }
        }
    }
    

提交回复
热议问题