简体   繁体   中英

Call method from abstract class when abstract method called in the derived class

I'm making a user interface in XNA with a custom control setup. I have a base abstract class called Clickable , this contains methods that are run when various actions happen, Ie; OnClick , OnRelease .

I have tried to implement listeners into this, i use the below two methods to get this to work:

public void RegisterClickListener(Action<Vector2> ClickMethod)
{
    listners.Add(ClickMethod);
}

public void OnClickMethod(Vector2 pos)
{
    foreach (Action<Vector2> func in listners)
        func(pos);
}

RegisterClickListener adds the method passed in the parameters to a list of methods to be called when the OnClickMethod method fires. OnClickMethod simply iterates through the list and calls each method.

I need a way to be able to call OnClickMethod each time my abstract method OnClick (bellow) is called. Currently i have to to manually invoke OnClickMethod each time i use OnClick , which is not ideal.

 public abstract void OnClick(Vector2 pos);

Is there a way i can do this while keeping OnClick abstract? Or will i have to take off the abstract and call base each time i use it?

You're looking for Template method pattern . Create a method which acts as a template(does some steps in fixed order), then give the client options to override only small portion of it.

public void OnClick(Vector2 pos)
{
    OnClickCore(pos);
    OnClickMethod(pos);
}

public abstract void OnClickCore(Vector2 pos);

Now OnClick is a template method which defines set of rules that need to be invoked when it is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM