How to Restrict creation of objects from certain class

2k views Asked by At

I have a 'Bank' class and a 'Branch' class. 'Branch' is inherited from 'Bank'. I want to allow ONLY 'Bank' object to create new 'Branch' objects. (e.g. only citi group can open new branches of citi banks).

What is the best design pattern to achieve this?

I am currently using friend class with private constructor. but I am not sure whether it's the right way to do it.

1

There are 1 answers

4
Luchian Grigore On

'Branch' is inherited from 'Bank'

There's your problem, you're using inheritance. You're looking for an abstract factory pattern, where the Bank is the branch creator, and provide access to constructor of branches only to their respective creators.

struct Branch  //abstract
{
    virtual ~Branch() = 0;
};
class CitiBranch : Branch
{
    friend class Citi; //only Citi can create instances of CityBranch
private:
    CitiBranch();
};

struct Bank
{
    virtual ~Bank() = 0;
    virtual Branch* createBranch() = 0;
}

struct Citi : Bank
{
    virtual Branch* creatBranch()
    {
        return new CityBranch;
    }
}

This programs to an interface rather than a concrete class. So you have Branch pointers and Bank pointers, and don't really need to know their exact type.

If you have a Bank* and call createBranch(), you'll get a Branch* back but it will point to a correct concrete object.