Ronald Meijboom
Ronald Meijboom

Reputation: 1574

Pattern for multiple methods with same implementation

What design pattern can be used when you have multiple classes with the same methods and implementation?

I thought about using the Facade pattern which provides acces to methods. But when I look at the class diagram it is not exactly what I want.

Another idea was to use an (abstract) class which implemented these methods and the classes will extend this (abstract) class.

The next method is defined in six different classes. There are multiple methods like this and it becomes difficult to maintain.

private void FactoryFaulted(object sender, EventArgs e)
    {
        ChannelFactory factory = (ChannelFactory)sender;

        try
        {
            factory.Close();
        }
        catch
        {
            factory.Abort();
        }
    }

Upvotes: 0

Views: 1667

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

Generally, the way that you deal with identical code is different from the way in which you deal with similar code. Design patterns, such as the Template Method Pattern, are helpful in reducing the amount of code that is similar among many classes, but not identical.

When the code is identical, you can put it in a static function, and reuse as-is:

internal static class FactoryHelper {
    // Note that your method is not using instance variables of the class,
    // making it an ideal candidate for making a static helper method.
    public static void FactoryFaulted(object sender, EventArgs e) {
        ChannelFactory factory = (ChannelFactory)sender;
        try {
            factory.Close();
        } catch {
            factory.Abort();
        }
    }
}

Upvotes: 1

Only a Curious Mind
Only a Curious Mind

Reputation: 2857

You can use the abstract class and extend this, or create a Helper class, and call in all classes like this:

public static Helper
{
    public static void FactoryFaulted(object sender, EventArgs e)
    {
        ChannelFactory factory = (ChannelFactory)sender;

        try
        {
            factory.Close();
        }
        catch
        {
            factory.Abort();
        }
    }
}

public class YourClass
{
   public void DoSomething()
   {
       var channelFactory = new ChannelFactory();
       Helper.FactoryFaulted(channelFactory, null);
   }
}

Upvotes: 3

Related Questions