简体   繁体   中英

Abstract class which concrete class to use? Design issue?

I have a design issue. I am modifying existing code and where I was instantiating new class. It's giving me errors due to turning the class into a Abstract class which I can understand. It's throwing an error because you can't create instances of abstract class.

I had this code below

ExampleProcessor pro = new ExampleProcessor();

but the ExmapleProcessor class is now turned into abstract class.

public abstract class ExmapleProcessor {
  public abstract void Method1();
  public abstract void Method2();
}

Child classes AExampleProcessor and BExampleProcessor.

public class AExampleProcessor : ExampleProcessor 
{  
  public override void Method1()  { //do something }
  public override void Method2()  { //do something }
}

public class BExampleProcessor : ExampleProcessor 
{
  public override void Method1()  { //do something }
  public override void Method2()  { //do something }
}

So this line is causing 42 errors "ExampleProcessor pro = new ExampleProcessor();" everywhere in my application.

I dont want to do

AExampleProcessor pro = new AExampleProcessor();

and

BExampleProcessor pro = new BExampleProcessor();

because I want my application to decide which class to use. How can I make it so it loads up the correct class?

I would like code examples please..

Create a factory:

public static class ExampleProcessorFactory
{
   public static ExampleProcessor Create()
   {
       if(IsFullmoon)
           return new ExampleProcessorA();
       else
           return new ExampleProcessorB();
   }
}

Then replace all calls to new ExampleProcessor() with calls to ExampleProcessorFactory.Create() . Now you've encapsulated the instantiation logic and the choosing of what concrete class to instantiate into one place where you can apply any logic to decide what class to instantiate. (The logic of deciding when to use which class might benefit from some improvement to be unrelated to the full moon.)

Since you want the application to decide which concrete subclass to use, I suggest you use a Factory pattern.
That way, the client code knows only that you are using an ExampleProcessor, and the implementation details remain hidden.

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