現在我正在開發一個用於識別照片中的對象的類,並且此類由多個組件(類)組成。例如,這是一個使用抽象工廠模式的例子嗎?
class PhotoRecognizer
{
public:
int perform_recogniton()
{
pPreProcessing->do_preprocessing();
pFeatureExtractor->do_feature_extraction();
pClassifier->do_classification()
}
boost::shared_ptr<PreProcessing> pPreProcessing;
boost::shared_ptr<FeatureExtractor> pFeatureExtractor;
boost::shared_ptr<Classifier> pClassifier;
}
在這個例子中,當我們使用這個類來進行識別,我們調用其他類PreProcessing
,FeatureExtractor
和Classifier
。正如你可以想象的那樣,有很多不同的方法來實現每個類。例如,對於Classifier
類,我們可以使用SVMClassfier
或NeuralNetworkClassifer
,它是基本類Classifier
的派生類。
class SVMClassifier: public Classifier
{
public:
void do_classification();
};
因此,通過使用PhotoRecognizer
類中的不同元素,我們可以創建不同種PhotoRecongnizer
。現在,我正在構建一個基準,以瞭解如何將這些元素結合在一起以創建最佳PhotoRecognizer
。一個解決方案,我能想到的就是用抽象工廠:
class MethodFactory
{
public:
MethodFactory(){};
boost::shared_ptr<PreProcessing> pPreProcessing;
boost::shared_ptr<FeatureExtractor> pFeatureExtractor;
boost::shared_ptr<Classifier> pClassifier;
};
class Method1:public MethodFactory
{
public:
Method1():MethodFactory()
{
pPreProcessing.reset(new GaussianFiltering);
pFeatureExtractor.reset(new FFTStatictis);
pClassifier.reset(new SVMClassifier);
}
};
class Method2:public MethodFactory
{
public:
Method1():MethodFactory()
{
pPreProcessing.reset(new MedianFiltering);
pFeatureExtractor.reset(new WaveletStatictis);
pClassifier.reset(new NearestNeighborClassifier);
}
};
class PhotoRecognizer
{
public:
PhotoRecognizer(MethodFactory *p):pFactory(p)
{
}
int perform_recogniton()
{
pFactory->pPreProcessing->do_preprocessing();
pFactory->pFeatureExtractor->do_feature_extraction();
pFactory->pClassifier->do_classification()
}
MethodFactory *pFactory;
}
所以當我用方法一進行照片的認可,我可以簡單地做到以下幾點:
Method1 med;
PhotoRecognizer recogMethod1(&med);
med.perform_recognition()
更進一步,我甚至可以使類PhotoRecognizer
更緊湊:
enum RecMethod
{
Method1, Method2
};
class PhotoRecognizer
{
public:
PhotoRecognizer(RecMethod)
{
switch(RecMethod)
{
case Method1:
pFactory.reset(new Method1());
break;
...
}
}
boost::shared_ptr<MethodFactory> pFactory;
};
因此,這裏是我的問題:是抽象工廠設計模式有充分理由在上述的情況呢?有其他解決方案嗎?謝謝。
這與C++無關,爲什麼標記在那裏? – Ceros
@Ceros演示代碼在C++ – feelfree
但你的問題是關於代碼設計而不是C++ – Ceros