1

for example:

public class A {}

public class B
{
    public void test()
    {
        A obj = A();
    }
}

I just looking for best way to remove dependency between class A and B, Or which design pattern is best suited for this if more classes added at sub classes level?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
ROOMY
  • 53
  • 8

2 Answers2

7

Receive an instance of A in the constructor. Even better is to have A inherit some interface and receive that interface in the constructor.

public interface IA {}
public class A : IA {}

public class B 
{
    public IA AInstance { get; set; }
    public B (IA a)
    {
        AInstance = a;
    }

    public void test()
    {
        /* do something with `AInstance` */
    }
}

Look into the concepts of Dependency Injection and Inversion of Control:

  1. What is dependency injection?
  2. What is Inversion of Control?

And wrap it all under the SOLID principals


If you can't get IA as a dependency but need to create a new instance of it in your B class then use the Factory design pattern and let B depend on some instance of ISomeFactory

Graham
  • 7,431
  • 18
  • 59
  • 84
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • Thanks - but I think here we need to use new keyword inside B class. and again there have dependent on each other. – ROOMY May 01 '17 at 08:21
  • thanks - I also think same but is there any other way in which we avoid to use new keyword inside B. – ROOMY May 01 '17 at 08:27
  • @ROOMY - If you have to instanciate a `B` class in `A` then I think rethink the design to see if it is really needed and if still then look into the `Factory` design pattern - and have a dependency on some `ISomeFactory` – Gilad Green May 01 '17 at 08:28
  • Awesome I got a badge from the reference to my documentation on the Factory Pattern! – Michael Brown Aug 17 '17 at 21:26
1

I'd suggest you'd use IoC as design pattern. It removes the dependency of your classes and makes it possible to mock your objects while unit testing

https://msdn.microsoft.com/en-us/library/aa973811.aspx

Nieksa
  • 354
  • 1
  • 7
  • 20
  • Dependency Injection should be enough – Myrtle May 01 '17 at 08:27
  • Well he asked for a design pattern ;) – Nieksa May 01 '17 at 08:31
  • Then we should tutor him design patterns should only be used when you have a problem they solve. Why guide someone to IoC when this is overkill? What he needs is design principles. in this case single responsibility and dependency inversion. – Myrtle May 01 '17 at 10:13