第三周的課學(xué)到有關(guān)面向?qū)ο蟮脑O(shè)計(jì)模式的東西。拋開課堂上講的三種不談,來說說常用的幾種設(shè)計(jì)模式。
一、Strategy模式
1、兩大原則
Strategy模式體現(xiàn)了如下的兩大原則:
1,針對(duì)接口編程,而不是針對(duì)實(shí)現(xiàn)編程。
2,多用組合,少用繼承。

二、Iterator模式
提供一種方法順序訪問一個(gè)聚合對(duì)象中各個(gè)元素, 而又不需暴露該對(duì)象的內(nèi)部表示。
這種設(shè)計(jì)模式非常普遍,
比如Java里面的:
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
以及C++ STL里面的 iterator使用 ++ 訪問。
三、Singleton模式
下面是個(gè)C++ singleton的類:
、、、
#ifndefSINGLETON_H
#defineSINGLETON_H
#include"synobj.h"
template
classSingleton{
CLASS_UNCOPYABLE(Singleton)
public:
staticT&Instance(){//Uniquepointofaccess
if(0==_instance){
Locklock(_mutex);
if(0==_instance){
_instance=newT();
atexit(Destroy);
}
}
return*_instance;
}
protected:
Singleton(){}
~Singleton(){}
private:
staticvoidDestroy(){//Destroytheonlyinstance
if(_instance!=0){
delete_instance;
_instance=0;
}
}
staticMutex_mutex;
staticT*volatile_instance;//Theoneandonlyinstance
};
template
MutexSingleton::_mutex;
template
T*volatileSingleton::_instance=0;
#endif
、、、
四、Factory Method模式
Factory Method模式在不同的子工廠類生成具有統(tǒng)一界面接口的對(duì)象,一方面,可以不用關(guān)心產(chǎn)品對(duì)象的具體實(shí)現(xiàn),簡化和統(tǒng)一Client調(diào)用過程;另一方面,可以讓整個(gè)系統(tǒng)具有靈活的可擴(kuò)展性。
abstract class BallFactory{
protectedabstractBallmakeBall();//FactoryMethod
}
classBasketballFactextendsBallFactory{
publicBallmakeBall(){//子類實(shí)現(xiàn)FactoryMethod決定實(shí)例化哪一個(gè)類的
returnnewBasketball();
}
}
classFootballFactextendsBallFactory{
publicBallmakeBall(){//子類實(shí)現(xiàn)FactoryMethod決定實(shí)例化哪一個(gè)類的
returnnewFootball();
}
}
classBasketballextendsBall{
publicvoidplay(){
System.out.println("playthebasketball");
}
}
classFootballextendsBall{
publicvoidplay(){
System.out.println("playthefootball");
}
}
abstractclassBall{
protectedabstractvoidplay();
}
publicclasstest{
publicstaticvoidmain(String[]args){
BallFactoryballFactory=newBasketballFact();
Ballbasketball=ballFactory.makeBall();
basketball.play();
ballFactory=newFootballFact();
Ballfootball=ballFactory.makeBall();
football.play();
}
}
這是幾種常用的設(shè)計(jì)模式,剩下的還有很多,畢竟有23種呢。剩下的有時(shí)間慢慢學(xué)習(xí)。
ps:沒找到簡書怎么寫代碼。看著亂糟糟的格式,真是蛋疼。