潇's profile老肖的地盘PhotosBlogListsMore Tools Help

Blog


    October 21

    Factory Method

    终于遇到一个比较熟悉的模式了,先上一段代码,根据书上类图实现的:

    class Product
    {

    };

    class ConcreteProduct : Product
    {
    };

    class Creator
    {
    private:
        Product* product;
    public:
        virtual Product*  FactoryMethod() { return 0;}
        void AnOperation() { product = FactoryMethod();}
    };

    class ConcreteProduct : Creator
    {
        Product* FactoryMethod() { return new ConcreteProduct();}
    };

    适用性:

    当一个类不知道它所必须创建的对象的类的时候。

    当一个类希望由它的子类来指定它所创建的对象的时候。

    当类将创建对象的职责委托给多个帮组子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。

    自然,工厂方法还有很多其他的实现方式,比如模板:

    class Creator

    {

    public:

        virtual Product* CreateProduct() = 0;

    };

    template <class TheProduct>

    class StandardCreator: public Creator

    {

    public:

        virtual Product* CreateProduct()

        {

            return new TheProduct;

        }

    };

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://seanxiaoxiao.spaces.live.com/blog/cns!7677365E5B9342DE!638.trak
    Weblogs that reference this entry
    • None