获取将包含的类的Singleton

时间:2013-03-24 22:39:53

标签: c++ class object pointers singleton

我目前有这个课程:

ActivityActivityManager(扩展Activity)。

我在Activity中有一个方法,它获得ActivityManager的单例对象。

过了一会儿,我看到我进入了“没有生命的生活”悖论,因为ActivityManager只能由编译器“创建”,AFTER Activity就是。那么,我该怎么做呢?

我的意思是,我怎样才能得到一个从第一个扩展的对象类?

我甚至不知道如何将它放在谷歌上,所以,请帮帮我!感谢

修改

简化Activity

class Activity
{
public:
    void start();
};

void Activity::start(void){
    // Start current Activity on the ActivityManager Stack
    ActivityManager *am;
    am = ActivityManager::getInstance();
    am->start(this);
}

简化ActivityManager

class ActivityManager: public Activity
{
private:
    // Singleton Object
    static ActivityManager *singleton;

public:
    // Singleton method to return defauld object instance
    static ActivityManager* getInstance(void);

    // Overload method, used to run others Activityes
    void start(Activity& activity);

};

// Singleton method to return default ActivityManager object instance
ActivityManager* ActivityManager::getInstance(){
    if(!singleton) singleton = new ActivityManager();

    return singleton;
}

// Function called on request to start new activity
void ActivityManager::start(Activity& activity){
}

1 个答案:

答案 0 :(得分:0)

我认为复合模式(http://en.wikipedia.org/wiki/Composite_pattern)更符合您的需求。

这将是一些变化(命名在模式方面有点紧张,但它们更像是你的代码):

class Activity
{
    public:
        virtual ~Activity();

        virtual void start();
        virtual void add(Activity*);
        virtual void remove(Activity*);

    private:
        Activity();
}



class ActivityManager : Activity
{
    public:
        ConcreteActivity();
        ~ConcreteActivity();

        void start();
        void add(Activity*);
        void remove(Activity*);

    private:
        list<Activity*> _activities;
}

void ActivityManager::start()
{
    list<Activity*>::const_iterator concreteActivity;

    for(concreteActivity = _activities.begin(), concreteActivity != _activities.end(); ++concreteActivity)
    {
        *concreteActivity->start();
    }
}

void ActivityManager::add(Activity* newActivity)
{
    _activities.push_back(newActivity);
}

void ActivityManager::remove(Activity* activityToDelete)
{
    _activities.remove(activityToDelete);
}




class SomeActivity : Activity
{
     public:
         SomeActivity();
         ~SomeActivity();

         void start();
}

class OtherActivity : Activity
{
     public:
         OtherActivity();
         ~OtherActivity();

         void start();
}

使用示例:

ActivityManager* manager = new ActivityManager();

SomeActivity* activity_one = new SomeActivity();
OtherActivity* activity_two = new OtherActivity();

manager->add(activity_one);
manager->add(activity_two);
manager->start();

如果你愿意的话,你仍然可以让ActivityManager成为Singleton。如果没有关于项目的任何其他信息,就无法想到更好的方法。