0

我目前有这个课程:

Activity, ActivityManager(扩展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){
}
4

1 回答 1

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。没有关于您的项目的任何其他信息,想不出更好的方法。

于 2013-03-25T01:42:34.460 回答