• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            Just enjoy programming

            #

            c++設計模式(九) 抽象工廠(Abstract Factory)

                  抽象工廠(Abstract Factory)模式看起來和前面看到的工廠方法很相似,只是它使用若干工廠方法(Factory Method)模式。每個工廠方法模式創建一個不同類型的對象。當創建一個工廠對象時,要決定將如何使用由那個工廠創建的所有對象。示例代碼如下(假設要創建一個通用的游戲環境,并且希望它能支持不同類型的游戲):
            #include<iostream>
            using namespace std;

            class Obstacle
            {
            public:
                virtual void action()=0;
            };

            class Player
            {
            public:
                virtual void interactWith(Obstacle*)=0;
            };

            class Kitty: public Player
            {
                virtual void interactWith(Obstacle *ob)
                {
                    cout<<"Kitty has encountered a";
                    ob->action();
                }
            };

            class KungFuGuy: public Player
            {
                virtual void interactWith(Obstacle* ob)
                {
                    cout<<"KungFuGuy now battles against a";
                    ob->action();
                }
            };
            class Puzzle: public Obstacle
            {
            public:
                void action(){cout<<"Puzzle"<<endl;}
            };

            class NastyWeapon: public Obstacle
            {
            public:
                void action(){cout<<"NastyWeapon"<<endl;}
            };

            //the abstract factory
            class GameElementFactory
            {
            public:
                virtual Player* makePlayer()=0;
                virtual Obstacle* makeObstacle()=0;
            };

            //concreate factories
            class KittiesAndPuzzles:public GameElementFactory
            {
            public:
                virtual Player* makePlayer(){return new Kitty;}
                virtual Obstacle * makeObstacle(){return new Puzzle;}
            };

            class KillAndDismember:public GameElementFactory
            {
            public:
                virtual Player* makePlayer(){return new KungFuGuy;}
                virtual Obstacle *makeObstacle(){return new NastyWeapon;}
            };


            class GameEnvironment
            {
                GameElementFactory* gef;
                Player* p;
                Obstacle *ob;
            public:
                GameEnvironment(GameElementFactory * factory)
                    :gef(factory),p(factory->makePlayer()),ob(factory->makeObstacle()){}
                void play(){p->interactWith(ob);}
                ~GameEnvironment()
                {
                    delete p;
                    delete ob;
                    delete gef;
                }
            };

            int main()
            {
                GameEnvironment
                    g1(new KittiesAndPuzzles),
                    g2(new KillAndDismember);
                g1.play();
                g2.play();
            }

            在此環境中,Player對象與Obstacle 對象交互,但是Player和Obstacle類型依賴于具體的游戲??梢赃x擇特定的GameElementFactory來決定游戲的類型,然后GameEnvironment控制游戲的設置和進行。在本例中,游戲的設置和進行很簡單,但是那些動作在很大程度上決定了游戲的結果。

            posted @ 2011-05-03 23:40 周強 閱讀(374) | 評論 (0)編輯 收藏

            c++設計模式(八) 工廠模式:封裝對象的創建

                 工廠模式不允許將創建對象的代碼散布于整個系統。如果程序中所有需要創建對象的代碼都轉到這個工廠執行,那么在增加新對象時所要做的全部工作就是只需修改工廠。這種設計時眾所周知的工廠方法模式的一種變體。由于每個面向對象應用程序都需要創建對象,并且由于人們可能通過添加新類型來擴展應用程序,工廠模式可能是所有設計模式中最有用的模式之一。實現工廠模式的一種方法就是在基類中定義一個靜態成員函數,示例如下:
            #include<iostream>
            #include<stdexcept>
            #include<cstddef>
            #include<string>
            #include<vector>

            using namespace std;

            class Shape
            {
            public:
                virtual void draw()=0;
                virtual void erase()=0;
                virtual ~Shape(){}
                class BadShapeCreation :public logic_error
                {
                public:
                    BadShapeCreation(string type):
                        logic_error("Cannot create type"+type){}
                };
                static Shape* factory(const string &type)
                    throw(BadShapeCreation);
            };

            class Circle:public Shape
            {
                Circle(){}
                friend class Shape;
            public:
                void draw(){cout<<"Circle::draw"<<endl;}
                void erase(){cout<<"Circle::erase"<<endl;}
                ~Circle(){cout<<"Circle::~Circle"<<endl;}
            };

            class Square:public Shape
            {
                Square(){}
                friend class Shape;
            public:
                void draw(){cout<<"Square::draw"<<endl;}
                void erase(){cout<<"Square::erase"<<endl;}
                ~Square(){cout<<"Square::~Square"<<endl;}
            };

            Shape *Shape::factory(const string & type)
                throw(Shape::BadShapeCreation)
            {
                if(type=="Circle")return new Circle;
                if(type=="Square")return new Square;
                throw BadShapeCreation(type);
            }

            char *sl[]={"Circle","Square","Square","Circle","Circle","Circle","Square"};

            int main()
            {
                vector<Shape*>shapes;
                try{
                    for(size_t i=0;i<sizeof sl/sizeof sl[0];i++)
                        shapes.push_back(Shape::factory(sl[i]));
                }catch(Shape::BadShapeCreation e)
                {
                    cout<<e.what()<<endl;
                    return -1;
                }
                for(size_t i=0;i<shapes.size();i++)
                {
                    shapes[i]->draw();
                    shapes[i]->erase();
                }
            }

            函數factory 允許以一個參數來決定創建何種類型的Shape。在這里,參數類型為string,也可以是任何數據集。為了確保對象的創建只能發生在函數factory()中,Shape的特定類型的構造函數被設為私有,同時Shape被聲明為友元類,因此factory()能夠訪問這些構造函數。

            參考: C++編程思想卷2

            posted @ 2011-05-03 23:12 周強 閱讀(1511) | 評論 (0)編輯 收藏

            c++設計模式(七) 職責鏈模式:嘗試采用一系列策略模式

                  職責鏈(Chain of Responsibility)模式也許被看做一個使用策略對象的“遞歸的動態一般化".此時提出一個調用,在一個鏈序列中的每個策略都試圖滿足這個調用。這個過程直到有一個策略成功滿足該調用或者到達序列的末尾才結束。在遞歸方法中,有個函數反復調用其自身至達到某個終止條件。在職責鏈中,一個函數調用自身,(通過遍歷策略鏈)調用函數的一個不同實現,如此反復直至達到某個終止條件。這個終止條件或者是已達到策略鏈的底部(這樣就會返回一個默認對象;不管能否提供這個默認結果,必須有個方法能夠決定該職責鏈搜索是成功還是失敗)或者是成功找到一個策略。
                 除了調用一個函數來滿足某個請求以外,鏈中的多個函數都有此機會滿足某個請求,因此它有點專家系統的意味。由于職責鏈實際上就是一個鏈表,它能夠動態創建,因此它可以看做是一個更一般的動態構建的switch語句。示例代碼如下:
            #include<iostream>
            #include<vector>

            using namespace std;


            enum Answer{NO,YES};

            class GimmeStrategy
            {
                public:
                    virtual Answer canIHave()=0;
                    virtual ~GimmeStrategy(){}
            };

            class AskMom: public GimmeStrategy
            {
                public:
                    Answer canIHave()
                    {
                        cout<<"Moom? can I have this?"<<endl;
                        return NO;
                    }
            };

            class AskDad: public GimmeStrategy
            {
                public:
                    Answer canIHave()
                    {
                        cout<<"Dad,I really need this!"<<endl;
                        return NO;
                    }
            };


            class AskGrandpa:public GimmeStrategy
            {
                public:
                    Answer canIHave()
                    {
                        cout<<"Grandpa , is it my birthday yet?"<<endl;
                        return NO;
                    }
            };

            class AskGrandma:public GimmeStrategy
            {
                public:
                    Answer canIHave()
                    {
                        cout<<"Grandma,I really love you!"<<endl;
                        return YES;
                    }
            };

            class Gimme:public GimmeStrategy
            {
                vector<GimmeStrategy*>chain;
                public:
                    Gimme(){
                        chain.push_back(new AskMom());
                        chain.push_back(new AskDad());
                        chain.push_back(new AskGrandpa());
                        chain.push_back(new AskGrandma());
                    }
                    Answer canIHave()
                    {
                        vector<GimmeStrategy*>::iterator it=chain.begin();
                        while(it!=chain.end())
                            if((*it++)->canIHave()==YES)
                                return YES;
                        cout<<"whiiiiiinnne!"<<endl;
                        return NO;
                    }
                    ~Gimme(){};
            };

            int main()
            {
                Gimme chain;
                chain.canIHave();
            }


            參考 :c++編程思想卷二

            posted @ 2011-05-03 14:01 周強 閱讀(679) | 評論 (1)編輯 收藏

            c++設計模式(六)策略模式:運行時選擇算法

                   前面模板方法模式是“堅持相同的代碼“,而被覆蓋的函數是“變化的代碼“。然而,這種變化在編譯時通過繼承被固定下來。按照“組合優于繼承“的格言,可以利用組合來解決將變化的代碼從“堅持相同的代碼“中分開的問題,從而產生策略(Strategy)模式。這種方法的一個明顯的好處:在程序運行時,可以插入變化的代碼。策略模式也加入“語境“,它可以是一個代理類,這個類控制著對特定策略對象的選擇和使用。
                   “策略“的意思就是:可以使用多種方法來解決某個問題,即條條大陸通羅馬。現在考慮一下忘記了某個人姓名時的情景。這里的程序可以用不同方法解決這個問題,實例代碼如下:
            #include<iostream>

            using namespace std;

            class NameStrategy
            {
                public:
                    virtual void greet()=0;
            };

            class SayHi: public NameStrategy
            {
                public:
                    void greet()
                    {
                        cout<<"Hi! How's it going?"<<endl;
                    }
            };

            class Ignore: public NameStrategy
            {
                public:
                    void greet()
                    {
                        cout<<"Pretend I don't see you)"<<endl;
                    }
            };

            class Admission:public NameStrategy
            {
                public:
                    void greet()
                    {
                        cout<<"I'm sorry ,I forgot your name."<<endl;
                    }
            };

            class Context
            {
                NameStrategy & strategy;
                public:
                    Context(NameStrategy & strat):strategy(strat){}
                    void greet(){strategy.greet();}
            };


            int main()
            {
                SayHi sayhi;
                Ignore ignore;
                Admission admission;
                Context c1(sayhi),c2(ignore),c3(admission);
                c1.greet();
                c2.greet();
                c3.greet();

            }

            Context::greet()可以正規地寫得更加復雜些,它類似模板方法模式,因為其中包含了不能改變的代碼。但在函數main()中可以看到,可以在運行時就策略進行選擇。更進一步的做法??梢詫顟B模式與Context對象的生存期間變化的策略模式結合起來使用。

            posted @ 2011-05-03 11:33 周強 閱讀(738) | 評論 (0)編輯 收藏

            c++設計模式(五)模板方法模式

                   應用程序結構框架允許從一個或一組類中繼承以便創建一個新的應用程序,重用現存類中幾乎所有的代碼,并且覆蓋其中一個或多個函數以便自定義所需要的應用程序。應用程序結構框架中的一個基本的概念是模板方法模式,它很典型地隱藏在覆蓋的下方,通過調用基類的不同函數來驅動程序運行。
                  模板方法模式的一個重要特征是它的定義在基類中(有時作為一個私有成員函數)并且不能改動,模板方法模式就是“堅持相同的代碼“。它調用其他基類函數(就是那些被覆蓋的函數)以便完成其工作,但是客戶程序員不必直接調用這些函數。驅動應用程序運行的“引擎”是模板方法模式,示例代碼如下:
            #include<iostream>

            using namespace std;

            class ApplicationFramework
            {
                protected :
                    virtual void customize1()=0;
                    virtual void customize2()=0;
                public:
                    void templateMethod()
                    {
                        for(int i=0;i<5;i++)
                        {
                            customize1();
                            customize2();
                        }
                    }
            };

            class MyApp: public ApplicationFramework
            {
                protected:
                    void customize1(){cout<<"Hello";}
                    void customize2(){cout<<"World!"<<endl;}
            };

            int main()
            {
                MyApp app;
                app.templateMethod();

            }

            參考:c++編程思想卷二

            posted @ 2011-05-03 11:15 周強 閱讀(492) | 評論 (0)編輯 收藏

            c++設計模式(四)適配器(Adapter)模式

            適配器(Adapter)模式接受一種類型并且提供一個對其他類型的接口。當給定一個庫或者具有某一接口的一段代碼,同事還給定另外一個庫或者與前面那段代碼的基本思想相同的一段代碼而只是表達式不一致時,適配器模式將十分有用。通過調整彼此的表達方式來適配彼此,將會迅速產生解決方法。

            實例代碼如下:
            //FibonacciGenerator.h, 斐波那契數列產生器類

            #ifndef FIBONACCIGENERATOR_H
            #define FIBONACCIGENERATOR_H

            class FibonacciGenerator
            {
                int n;
                int val[2];
                public:
                    FibonacciGenerator():n(0){val[0]=val[1]=0;}
                    int operator()()
                    {
                        int result=n>2?val[0]+val[1]:n>0?1:0;
                        ++n;
                        val[0]=val[1];
                        val[1]=result;
                        return result;
                    }
                    int count(){return n;}
            };
            #endif

            也許讀者希望利用這個產生器來執行STL數值算法操作。遺憾的是,STL算法只能使用迭代器才能工作,這就存在接口不匹配的問題。解決方法就是產生一個適配器。代碼如下。
            #include<iostream>
            #include<numeric>
            #include"FibonacciGenerator.h"

            using namespace std;

            class FibonacciAdapter
            {
                FibonacciGenerator f;
                int length;
                public:
                    FibonacciAdapter(int size):length(size){}
                    class iterator;
                    friend class iterator;
                    class iterator:public std::iterator<std::input_iterator_tag,FibonacciAdapter,ptrdiff_t>
                    {
                        FibonacciAdapter& ap;
                        public:
                            typedef int value_type;
                            iterator(FibonacciAdapter &a):ap(a){}
                            bool operator==(const iterator &)const{
                                return ap.f.count()==ap.length;
                            }
                            bool operator!=(const iterator &x)const
                            {
                                return !(*this==x);
                            }

                            int operator*()const{return ap.f();}
                            iterator& operator++(){return *this;}
                            iterator operator++(int){return *this;}
                    };
                    iterator begin(){return iterator(*this);}
                    iterator end(){return iterator(*this);}
            };

            int main()
            {
                const int SZ=20;
                FibonacciAdapter a1(SZ);
                cout<<"accumulate:"<<accumulate(a1.begin(),a1.end(),0)<<endl;
            }



            posted @ 2011-05-03 10:49 周強 閱讀(362) | 評論 (0)編輯 收藏

            c++設計模式(三)代理模式(Proxy)與狀態模式(State)模式

                  代理(Proxy)模式,狀態(State)模式都提供一個代理類。代碼與代理類打交道,而實際工作的類隱藏在代理類背后。當調用代理類中的一個函數時,代理類僅轉而去調用實現類中的相應的函數。這兩種模式是如此相似,從結構上看,可以認為代理模式只是狀態模式的一個特例。但是這兩個模式的內涵是不一樣的。
                  基本思想很簡單:代理類派生來自一個基類,由平行地派生來自同一個基類的一個或多個類提供實際的實現。當一個代理對象被創建的時候,一個實現對象就分配給了它,代理對象就將函數調用發給實現對象。
                  從結構上來看,代理模式和狀態模式的區別很簡單:代理模式只有一個實現類,而狀態模式有多個(一個以上)實現。認為這兩種設計模式的應用也不同:代理模式控制對其實現類的訪問,而狀態模式動態地改變其實現類。
            (1)代理模式例子:
            #include<iostream>

            using namespace std;

            class ProxyBase
            {
                public:
                    virtual void f()=0;
                    virtual void g()=0;
                    virtual void h()=0;
                    virtual ~ProxyBase(){}
            };


            class Implementation :public ProxyBase
            {
                public:
                    void f(){cout<<"Implementation.f()"<<endl;}
                    void g(){cout<<"Implementation.g()"<<endl;}
                    void h(){cout<<"Implementation.h()"<<endl;}
            };


            class Proxy: public ProxyBase
            {
                ProxyBase *implementation;
                public:
                    Proxy(){implementation=new Implementation();}
                    ~Proxy(){delete implementation;}


                    void f(){implementation->f();}
                    void g(){implementation->g();}
                    void h(){implementation->h();}
            };

            int main()
            {
                Proxy p;
                p.f();
                p.g();
                p.h();
            }

            (2)狀態模式
            #include<iostream>

            using namespace std;

            class Creature
            {
                class State
                {
                    public:
                        virtual string response()=0;
                };

                class Frog : public State
                {
                    public:
                        string response(){return "Ribbet!";}
                };

                class Prince:public State
                {
                    public:
                        string response(){return "Darling!";}
                };

                State *state;
                public:
                    Creature(): state(new Frog()){}
                    void greet()
                    {
                        cout<<state->response()<<endl;
                    }
                    void kiss()
                    {
                        delete state;
                        state=new Prince();
                    }
            };


            int main()
            {
                Creature creature;
                creature.greet();
                creature.kiss();
                creature.greet();
            }

            posted @ 2011-04-28 16:04 周強 閱讀(727) | 評論 (0)編輯 收藏

            c++設計模式( 二) 命令:選擇操作

                  命令(command)模式的結構很簡單,但是對于消除代碼間的耦合,清理代碼去有著重要的影響。從最直觀的角度來看,命令模式就是一個函數對象:一個作為對象的函數。通過將函數封裝為對象,就能夠以參數的形式將其傳遞給其他函數或者對象,告訴它們在履行請求的過程中執行特定的操作。可以說,命令模式是攜帶行為信息的信使。一個簡單的例子如下:
            #include<iostream>
            #include<vector>

            using namespace std;

            class Command
            {
                public:
                    virtual void execute()=0;
            };


            class Hello: public Command
            {
                public:
                    void execute(){cout<<"hello ";}
            };


            class World : public Command
            {
                public:
                    void execute(){cout<<"world!";}
            };

            class IAm:public Command
            {
                public:
                    void execute(){cout<<"I'm the command pattern!";}
            };

            class Macro
            {
                vector<Command *>commands;
                public:
                    void add(Command *c){commands.push_back(c);}
                    void run()
                    {
                        vector<Command*>::iterator it=commands.begin();
                        while(it!=commands.end())
                        {
                            (*it++)->execute();
                            cout<<endl;
                        }
                        
                    }
            };


            int main()
            {
                Macro macro;
                macro.add(new Hello);
                macro.add(new World);
                macro.add(new IAm);
                macro.run();
            }

                  命令模式的主要特點是允許向一個函數或者對象傳遞一個想要的動作。上述例子提供了將一系列需要一起執行的動作集進行排隊的方法。在這里,可以動態創建新的行為,某些事情通常只能通過編寫新的代碼來完成,而在上述例子中可以通過解釋一個腳本來實現。

            參考:c++編程思想2

            posted @ 2011-04-28 14:26 周強 閱讀(408) | 評論 (0)編輯 收藏

            c++設計模式(一) 單件(Singleton)

            設計模式或許是面向對象設計方法學前進過程中的最新,最重要的一步。設計模式當今已成為面向對象程序設計的重要部分。

            單件也許是最簡單的設計模式,它是允許一個類有且僅有一個實例的方法。創建一個單件模式的關鍵是防止客戶程序員獲得任何控制其對象生存期的權利。為了做到這一點,聲明所有的構造函數為私有,并且防止編譯器隱式生成任何構造函數。注意,拷貝構造函數和賦值操作符(這兩個故意沒有實現,,因為它們根本不會被調用)被聲明為私有,以便防止任何這類復制動作產生。這種方法并沒有限制只創建一個對象。這種技術也支持創建有限個對象的對象池。

            下面的程序顯示在c++中如何實現一個單件模式
            #include<iostream>

            using namespace std;


            class Singleton
            {
                static Singleton s;
                int i;
                Singleton(int x):i(x){}
                Singleton & operator=(Singleton &); //disallowed
                Singleton(const Singleton &);

            public:
                static Singleton & instance(){return s;}
                int getValue(){return i;}
                void setValue(int x){i=x;}
            };


            Singleton Singleton::s(47);


            int main()
            {
                Singleton &s =Singleton::instance();
                cout<<s.getValue()<<endl;
                Singleton &s2=Singleton::instance();
                s2.setValue(9);
                cout<<s.getValue()<<endl;
            }


            參考:c++ 編程思想 2

            posted @ 2011-04-28 10:41 周強 閱讀(439) | 評論 (0)編輯 收藏

            Web Bench

            今天開始要看nginx 源碼了,首先先看一個web服務器壓力測試工具Web Bench 。

            Web Bench is very simple tool for benchmarking WWW or proxy servers. Uses fork() for simulating multiple clients and can use HTTP/0.9-HTTP/1.1 requests. This benchmark is not very realistic, but it can test if your HTTPD can realy handle that many clients at once (try to run some CGIs) without taking your machine down. Displays pages/min and bytes/sec. Can be used in more aggressive mode with -f switch.

            Web Bench 下載主頁 http://home..cz/~cz210552/webbench.html


            用Web Bench 簡單測試下nginx服務器的性能。結果如下
            測試參數 10000個用戶并發請求30秒




            posted @ 2011-04-26 14:50 周強 閱讀(271) | 評論 (0)編輯 收藏

            僅列出標題
            共6頁: 1 2 3 4 5 6 
            久久九九久精品国产免费直播| 久久丫精品国产亚洲av| 国产精品久久国产精品99盘| 久久av无码专区亚洲av桃花岛| 久久精品国产亚洲AV无码偷窥 | 午夜久久久久久禁播电影| 国产aⅴ激情无码久久| 久久国产亚洲精品无码| 久久久国产精品福利免费| 久久99热这里只有精品国产| 久久综合亚洲鲁鲁五月天| 久久se精品一区二区| 久久无码精品一区二区三区| 人妻无码久久一区二区三区免费 | 精品久久综合1区2区3区激情| 免费一级做a爰片久久毛片潮| 日本欧美久久久久免费播放网| 精品欧美一区二区三区久久久| 国产精品久久久香蕉| 久久免费精品一区二区| 久久婷婷五月综合色奶水99啪 | 热99RE久久精品这里都是精品免费| 久久丫精品国产亚洲av不卡| 久久久久亚洲AV综合波多野结衣 | 精品久久久久久无码人妻热| 久久综合给合久久狠狠狠97色69 | 伊人久久大香线焦AV综合影院| 91久久精品视频| 国内精品久久人妻互换| 亚洲七七久久精品中文国产 | 一本色综合网久久| 热久久国产欧美一区二区精品| 久久99国内精品自在现线| 欧美黑人激情性久久| 久久精品中文字幕有码| 成人精品一区二区久久| 久久99国产精一区二区三区| 精品九九久久国内精品| 99久久精品毛片免费播放| 久久久久久人妻无码| 日韩精品无码久久久久久|