Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implement similar methods of two different classes? [closed]

I have two classes (A and B) which implements the same interface (I) in C#. The interface have 5 methods to implement. Implementations of two of those methods are almost the same in both A and B except each implemetation uses a different variable. Here is the abstract layout of my classes.

class A : I
{
     Folder folder;
     void method()
     {
        //implementation uses ``folder``
     }

class B : I
{
     List list;
     void method()
     {
        //implementation uses ``list``
     }
}

Because the implementation of Method is the same (except the one parameter) I want to have implement Method only once. What is the best solution according of design patterns? one simple option is to define a third class which implements Methodand takes one parameter (either list or folder) and then call it within the Method of A and B. Any other solution?

------------Edit---------------

I don't want my Method to get any extra parameter. Under such circumstances, isn't static util class a better option than defining an abstract class?

like image 978
HHH Avatar asked Dec 11 '25 19:12

HHH


1 Answers

You can create a shared abstract base class which takes a T generic parameter and implements I<T>. That same T will be passed to Method, which will be implemented in the base class:

public interface I<T>
{
    void Method(T t);
}

public abstract class Base<T> : I<T>
{
            public Base(T t)
            {
                  this.param = t;
            }

            private readonly T param;
    public void Method()
    {
        // Do stuff
    }
}

public class A : Base<Folder>
{
          public A(Folder folder) : base(folder)
          { }
}

public class B : Base<List>
{
          public B(List list) : base(list)
          { }
}

public class Folder { }
public class List { }

Now, you can do:

static void Main()
{
    var a = new A(new Folder());
    a.Method();

    var b = new B(new File());
    b.Method();
}
like image 179
Yuval Itzchakov Avatar answered Dec 13 '25 10:12

Yuval Itzchakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!