Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern suggestion needed

I need a programming pattern but I couldn't figure out what it will be. I am not even sure if what I want is possible or not. Lets say I have a Class A and 10 class inherited from A. What I want is call the same method Method Print() implemented differently on each inherited class, but all of them need to repeat a same method of Class A.

Class A
{
    public virtual void Print()
    { 
    }
    protected void StartingProcedure()
    {
        /// something 
    }
    protected void EndingProcedure()
    {
        /// something 
    }
}

Class A_1 : A
{
    public override void Print()
    {
        StartingProcedure();
        /// class specific print operation
        EndingProcedure();
    }
}

Class A_2 : A
{
    public override void Print()
    {
        StartingProcedure();
        /// class specific print operation
        EndingProcedure();
    }
}

As you see I dont want to keep writing StartingProcedure(); on each overridden Print method. I want to automate that procedure, when I inherit a new class from A I don't want to mind the Starting and Ending procedures, i want to just write the class specific print operation. Is there any pattern that will provide me this kind of a class behaviour?

BTW I work with C#

like image 752
Tolga Evcimen Avatar asked Dec 12 '22 09:12

Tolga Evcimen


1 Answers

Class A
{
    public void Print()
    { 
        StartingProcedure();
        SpecificPrint();
        EndingProcedure();
    }
    protected void StartingProcedure()
    {
        /// something 
    }
    protected void EndingProcedure()
    {
        /// something 
    }
    protected virtual SpecificPrint() // could possibly be abstract
    {
    }
}

Class A_1 : A
{
    public override void SpecificPrint()
    {
        /// class specific print operation
    }
}

Class A_2 : A
{
    public override void SpecificPrint()
    {
        /// class specific print operation
    }
}
like image 68
Rik Avatar answered Dec 15 '22 00:12

Rik