简体   繁体   中英

Parent method that chooses child class (C#)

I'm trying to avoid duplicate blocks of code--each dealing with different children of a parent. Here is an example of what I would like to avoid:

if (FormNumber == 0)
    {  
    Child1 obj = new Child1()  
    statements;
    }
else
    {  
    Child2 obj = new Child2()  
    statements;
    }

I would like to pass FormNumber to the parent class and use a parent function to determine which child class is used. I'm imagining a parent function like:

public Parent GetChild(int F)  
    {  
        if (FormNumber == 0)
            return new Child1();
        else
            return new Child2();
    } 

and then in the main function

Parent obj = new Parent();  
Child? newobj = obj.GetChild(FormNumber);  
statements;

The problem is I need to figure out how to fill in the ? with the right Child class.

You are looking for factory / strategy pattern. Get them implement a similar interface and have it:

IChild newobj = obj.GetChild(FormNumber);  

You need to set up an inheratance hierarchy for Child . If you set up a common interface for Child1 and Child2 then you can do the following:

Parent obj = new Parent();  
IChild newobj = obj.GetChild(FormNumber); 
// newobj may be a Child1 or Vhild2 object.

The hiearrchy may look like:

public interface IChild {
    public methods();
}

public class Child1 : IChild {}

public class Child2 : IChild {}

Your method could then look like:

public IChild GetChild(int F)  
{  
    if (FormNumber == 0)
        return new Child1();
    else
        return new Child2();
} 

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