我意识到在C++中有很多关于朋友类的问题.不过,我的问题与具体情况有关.鉴于以下代码,以这种方式使用朋友是否合适?
class Software
{
friend class SoftwareProducer;
SoftwareProducer* m_producer;
int m_key;
// Only producers can produce software
Software(SoftwareProducer* producer) : m_producer(producer) { }
public:
void buy()
{
m_key = m_producer->next_key();
}
};
class SoftwareProducer
{
friend class Software;
public:
Software* produce()
{
return new Software(this);
}
private:
// Only software from this producer can get a valid key for registration
int next_key()
{
return ...;
}
};
Run Code Online (Sandbox Code Playgroud)
谢谢,
最好的祝福,
当然,这是完全合理的.基本上你所做的与工厂模式非常相似.我没有看到任何问题,因为你的代码似乎暗示每个Software对象都应该有一个指向其创建者的指针.
虽然,通常你可以避免使用像SoftwareProducer这样的"Manager"类,并且只需要在Software中使用静态方法.因为似乎只有一个SoftwareProducer.也许这样的东西:
class Software {
private:
Software() : m_key(0) { /* whatever */ }
public:
void buy() { m_key = new_key(); }
public:
static Software *create() { return new Software; }
private:
static int new_key() { static int example_id = 1; return example_id++; }
private:
int m_key;
};
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
Software *soft = Software::create();
soft->buy();
Run Code Online (Sandbox Code Playgroud)
当然,如果您计划拥有多个SoftwareProducer对象,那么您所做的似乎是合适的.