Abstract Factory模式示例(使用Locki类库)

本文试图借助Loki类库中的Singleton组件和AbstractFactory组件来应用Abstract Factory模式。
示例代码如下:

#include <iostream>
#include <memory>
#include "AbstractFactory.h"
#include "Singleton.h"
using namespace std;
using namespace Loki;
// Abstract products A and B
struct A { virtual ~A(){} };
struct B { virtual ~B(){} };
// Concrete products A1 and B1
struct A1: public A
{
    A1() { cout << "A1::ctor" << endl; }
};
struct B1: public B
{
    B1() { cout << "B1::ctor" << endl; }
};
// Concrete products A2 and B2
struct A2: public A
{
    A2() { cout << "A2::ctor" << endl; }
};
struct B2: public B
{
    B2() { cout << "B2::ctor" << endl; }
}; 
// Traditional method begins
class AbstractFactory1 
{ 
public:     
    virtual A* CreateA() = 0;    
    virtual B* CreateB() = 0;
};
class ConcreteFactory1 : public AbstractFactory1
{
public:
    virtual A* CreateA() { return new A1(); }
    virtual B* CreateB() { return new B1(); }    
    static ConcreteFactory1& Instance() {
        static ConcreteFactory1 instance;
        return instance;
    }
protected:
    ConcreteFactory1() {}
private:
    ConcreteFactory1(const ConcreteFactory1&);
    ConcreteFactory1& operator=(const ConcreteFactory1&);
};
class ConcreteFactory2 : public AbstractFactory1
{
public:
    virtual A* CreateA() { return new A2(); }
    virtual B* CreateB() { return new B2(); }    
    static ConcreteFactory2& Instance() {
        static ConcreteFactory2 instance;
        return instance;
    }
protected:
    ConcreteFactory2() {}
private:
    ConcreteFactory2(const ConcreteFactory2&);
    ConcreteFactory2& operator=(const ConcreteFactory2&);
};
// Traditional method ends
// Loki method begins
typedef AbstractFactory<TYPELIST_2(A, B)> AF;
typedef SingletonHolder<ConcreteFactory<AF, OpNewFactoryUnit, TYPELIST_2(A1, B1)> > SCF1;
typedef SingletonHolder<ConcreteFactory<AF, OpNewFactoryUnit, TYPELIST_2(A2, B2)> > SCF2;
// Loki method ends
void main()
{
    cout << "Traditional method:" << endl;
    // Create all concrete products using traditional method
    auto_ptr<A> pTA1(ConcreteFactory1::Instance().CreateA());
    auto_ptr<B> pTB1(ConcreteFactory1::Instance().CreateB());
    A *pTA2 = ConcreteFactory2::Instance().CreateA();
    delete pTA2;
    B *pTB2 = ConcreteFactory2::Instance().CreateB();
    delete pTB2;
    cout << "Loki method:" << endl;
    // Create all concrete products using Loki method
    auto_ptr<A> pLA1(SCF1::Instance().Create<A>());
    auto_ptr<B> pLB1(SCF1::Instance().Create<B>());
    A *pLA2 = SCF2::Instance().Create<A>();
    delete pLA2;
    B *pLB2 = SCF2::Instance().Create<B>();
    delete pLB2;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值