C # How to make factory method return subclass type

[BASIC EDITORS, my first post was somewhat misleading. My sentences]

For a class such as:

public class DatabaseResult{
    public bool Successful;
    public string ErrorMessage;     

    //Database operation failed
    public static DatabaseResult Failed(string message) {
         return new DatabaseResult{
             Successful = true,
             ErrorMessage = message
         };
    }
}

How can I implement subclasses to add additional properties to represent data related to a particular operation (for example, MatchedResult in the case of a SELECT query) without having to implement this static failure function? If I try to use regular inheritance, the return type will have a parent class. For instance:

DoThingDatabaseResult : DatabaseResult {
     public IEnumerable<object> SomeResultSet;
     public static Successful(IEnumerable<object> theResults){
          return new DoThingDatabaseResult {
               Successful = true,
               ErrorMessage = "",
               SomeResultSet = theResults
          };
     }
     //public static DatabaseResult Failed exists, but it the parent type!
}

The goal is to avoid having to copy the old Failed function for each implementation of the subclass.

+4
source share
4 answers

Make it recursively generic:

public class BankAccount<T> where T : BankAccount<T>, new()
{
    public T SomeFactoryMethod() { return new T(); }
}

public class SavingsAccount: BankAccount<SavingsAccount>{}

, factory , .

+4

, . - factory :

public class BankAccount
{
}

public class SavingsAccount : BankAccount
{
}

public static class BankAccountFactory
{
    public static T Create<T>() where T : BankAccount, new()
    {
        return new T();
    }
}

factory . BankAccount factory.

+2

, StriplingWarrior. , static factory. , a c - . , factory .

 private void Testit()
    {
        var a = SavingsAccount.Factory();
        var c = CheckingAccount.Factory();
        //var b = BankAccount.Factory(); //can't do this
    }


public class BankAccount<T> where T : BankAccount<T>, new()
{
    public static T Factory()
    {
        return new T();
    }
}

public class SavingsAccount : BankAccount<SavingsAccount>
{
}

public class CheckingAccount : BankAccount<CheckingAccount>
{
}
+1

, . BankAccount/SavingsAccount, , . , factory, , factory. , factory ...

public class BankAccountFactory { public virtual GetAccount() { return new BankAccount(); } }
public class SavingsAccountFactory : BankAccountFactory { public override GetAccount() { return new SavingsAccount(); } }

? .

, , - , , .

public BankAccount GetAccount(AccountType type) { /* */ }

public BankAccount GetAccount() { /* Access config */ }

: - , , ...

0
source

Source: https://habr.com/ru/post/1548122/


All Articles