samedi 10 juillet 2021

How to implement this design pattern without using friend?

In section 15.9 of C++ Primer 5th edition by Lippman, the section implements a design pattern where an interface hides the inheritance hierarchy. It's basically an abstract class, Query_base, whose children are WordQuery, NotQuery, and BinaryQuery. BranchQuery is an abstract base class from which AndQuery and OrQuery are derived.

The Query_base hierarchy is not made available to the user directly but is accessibly via pointer by an interface class called Query. User can interact only with the Query class to run queries like below:

Query q = Query("fiery") & Query("bird") | Query("wind")

The operators create objects of the typeQuery_base, e.g., the '&' creates an AndQuery, the '~' generates a NotQuery and then its saved as pointer in the Query class. The aim is to search a text document using the query rules.

Query_base class is defined as:

class Query_base {
    friend class Query;
protected:
    virtual ~Query_base() = default;
private:
    virtual QueryResult eval(const TextQuery&) const = 0;
    virtual std::string rep() const = 0;
}

Query class is defined as:

class Query {
    friend Query operator~(const Query&);
    friend Query operator|(const Query&, const Query&);
    friend Query operator&(const Query&, const Query&);
public:
    Query(const std::string&);
    QueryResult eval(const TextQuery &t) const { return q->eval(t); }
    std::string rep() const { return q->rep(); }
private:
    Query(std::shared_ptr<Query_base> query) : q(query) { }
    std::shared_ptr<Query_base> q;

In this design Query_base inheritance hierarchy is totally hidden by exposing a lean interface in the form of Query class to the user. Users can't directly interact with Query_base class as its members are non-public. Also, Query can access Query_base because it is a friend class.

In languages which doesn't have the concept of friend e.g Java, C#, how can one implement this kind of pattern where an interface class hides the inheritance hierarchy and user can only interact via the interface class?

Aucun commentaire:

Enregistrer un commentaire