简体   繁体   中英

Should I use a factory pattern?

I currently have a class named ConfigProfile factory and it contains methods for say a default profile, current settings, ect. This class gets used internally by my Profile service. I was thinking that it would be better to simply make this a true factory and just create the appropriate Profile Service for each of the products we are configuring.

    public string GetDefaultProfile(string product)
    {
        if (string.IsNullOrEmpty(product))
        {
            throw new ArgumentNullException("product");
        }

        string profile = null;

        if (product.Contains("Product 1", StringComparison.CurrentCultureIgnoreCase) ||
            product.Contains("product1", StringComparison.CurrentCultureIgnoreCase))
        {
            profile = Resources.product1DefaultProfile;
        }

        return profile;
    }

that is only one product there, but we have several more which means I will have to add more if statements for each one. The profile service already has an interface and is what gets used for most of my program. Also there are several methods that use this same way of doing things. So would a factory that returns the appropriate profile service based on product name be a better solution or is there something else I could do?

Edit: This is one of the simpler methods in this class. the more complex one is the one that retrieves the current system settings from the required places. Like all products have IIS settings, but some will have theme support while others will have database configuration to do.

Factory is a very good solution. It allows you to hide the configuration complexity behind a simple interface.

If you need to be able to configure it at run-time/start-up, combine with Strategy.

Both solutions - static factory or Strategy - can be combined with Prototype. Prototype would be useful as an optimization, if you often use the same profile, and it's read-only.

EDIT: You are probably using Prototype already. Your sample code looks like you are copying/referencing a profile rather than building it as a complex product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM