factory method design pattern

2019-03-28 13:22发布

According to the book:

The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

Say I have a Creator class:

class Product; //this is what the Factory Method should return
class Creator {
    public:
        Creator()   //ctor
        { //... }

        virtual Product make(//args)
        { //... }
}

Ok, that's my Creator class, but I don't understand

The Factory method lets a class defer instantiation to subclasses

What does it have to do with subclasses? And what am I supposed to use subclasses for?

Anyone can give me some example?

7条回答
贪生不怕死
2楼-- · 2019-03-28 13:40

I can only assume he means this:

class Product; //this is what the Factory Method should return
class Box : Product;

class Creator {
    public:
        Creator()   //ctor
        { //... }

        virtual Product* make(//args) = 0;
};

class BoxCreator{
    public:
        BoxCreator()
        {}
        virtual Product* make()
        {}
};

Creator* pCreator = new BoxCreator;
Product* pProduct = pCreator->make(); //will create a new box

However this is not a standard way to create a factory.

查看更多
趁早两清
3楼-- · 2019-03-28 13:42

Simple and short:

In the factory, it is checked which "subclass" is requested to instantiate so "let the subclasses decide which class to instantiate"
(You use conditional statements in factory class where decision has to be made.)

"define an interface or abstract class for creating an object". obviously, you store the object into interface's reference and the client is unaware which concrete class's object is returned. (So you defined an interface to create an object).

查看更多
仙女界的扛把子
4楼-- · 2019-03-28 13:51

I have the same confusion "let the subclasses decide which class to instantiate " -Because in implementation factory method using new to create an object" - I refer Head first design pattern book in which its clearly stated about this as follows - "As in the official definition you will hear often developers says that let the subclass decide which class to instantiate .They say "decides"not because the pattern allows subclass themselves to decide runtime ,but because the creator class is written w/o knowledge of the actual product that will be created ,which is decided purely by the choice of the subclass that is used "

查看更多
看我几分像从前
5楼-- · 2019-03-28 13:52

Providing such examples in pseudo-code is a bit confusing, the pattern is very language-dependent. Your example looks like in C++, but it's invalid in C++ because make returns Product by value. This is completely against the main goal of Factory - to return a reference (pointer in C++ case) to base class. Some answers take this as C# or Java (I guess) when others as C++.

Factory pattern relies on polymorphism. The key point is to return a reference to base Product class. Children of Factory will create instances of concrete classes.

查看更多
手持菜刀,她持情操
6楼-- · 2019-03-28 13:55

Product Make() will make the correct type (subclass) of product based on certain conditions and "defer" the actual instantiation to the specific products.

(psuedo code)

public class Product
{
    public static Product Make()
    {
        switch(day_of_week)
        {
           case Monday: return new Honey(1.1);
           case Wednesday: return new Milk(3.6);
           case Thurday: return new Meat(0.5);
           case Friday: return new Vegetable(1.3);
           case Saturday: return new Vegetable(2.3); // more expensive on saturday, only factory need to know
           default: return null; // off day!
        }
    }

    // returns price based on underlying product type and hidden/auto conditions (days of week)
    public virtual void GetPrice() { return Price; }

    // sometimes a factory can accept a product type enum
    // From API POV, this is easier at a glance to know avaliable types.
    pubic enum Type { Milk, Honey, Meat, Vegetable };

    public static Product Make(Type, Day)
    {
        // create the specified type for the specified day.
    }
}

public class Honey : Product { Price = arg; }
public class Milk : Product { Price = arg; }
public class Meat : Product { Price = arg; }
public class Vegetable : Product { Price = arg; }

Factory hides the required conditional details for constructing the various product types. Secondly, IMHO, from the API user point of view, it is usually easier to see what product types there are (usually from an enum) and easier to create them from a single point of creation.

查看更多
甜甜的少女心
7楼-- · 2019-03-28 13:59

Factory pattern merely means that there is some Factory class or method whose responsibility is to create objects for you; instead of you instantiating them yourself. Much like cars are built in factories so you don't have to.

It has nothing to do with sub classes however the author might be trying to say that factory can often return you derived implementation of a base class based on your parameters because that subclass may do what you're asking for in parameters.

For example WebRequest.Create("http://www.example.com") would return me HttpWebRequest but WebRequest.Create("ftp://www.example.com") would return me FtpWebRequest because both have different protocols which are implemented by different classes but the public interface is same so this decision doesn't have to be taken by consumer of my API.

查看更多
登录 后发表回答