samedi 20 mars 2021

Is it OK that parent class know the type of derived classes?

Is it ok that parent class knows the type of it's derived classes via a generic parameter?

class Cloneable<T> where T : is Cloneable {
    abstract T clone();
}

class A : Cloneable<A> {
    override A Clone() {
         // The child class knows how to clone itself.
         return new Child(...);  
    }
}

In the base class (Cloneable), I have an abstract method (Clone) that should be implemented in derived classes.
I want that the return type of Clone() method in the base class be a derived class (A).

Does this pattern violate any software design principle? Do you know any similar design in .Net class Library or Java?

Aucun commentaire:

Enregistrer un commentaire